2011-12-19 107 views
0

我更改了代码,以便可以直接插入数据库。现在我遇到了一行代码$database->bindParam(':name', $name[0][$i]);的问题。这给了我错误Fatal error: Call to undefined method PDO::bindParam()我该如何解决这个问题?使用预处理语句将数据插入数据库pdo

$hostname = 'XXX'; 
$database = 'XXX'; 
$username = 'XXX'; 
$password = 'XXX'; 
$database = new PDO("mysql:host=$hostname;dbname=$database", $username, $password); 

function get_data($url) 
{ 
    $ch = curl_init(); 
    $timeout = 5; 
    curl_setopt($ch,CURLOPT_URL,$url); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
} 

$html = get_data($_GET['url']); 
preg_match_all('/\<font face\=\"Arial\"\>\<strong\>(.*)\<br\>\<font color/', $html, $name); 
preg_match('/\<strong\>([A-Z\s0-9]+) BIRTHDAYS\<\/strong\>/', $html, $date); 

for ($i=0, $n=count($name[1]); $i<$n; ++$i) {  
     try { 
      $insert = $database->prepare("INSERT INTO bday (name, birthdate) VALUES (:name, :date)"); 

      $database->bindParam(':name', $name[0][$i]); 
      $database->bindParam(':date', $date[1]); 

      $insert->execute(); 
     } 

     catch (PDOException $e) { 
      echo $e->getMessage(); 
     } 
} 
+2

有自动递增的主键简单的插入,该数据库将采取其他 – 2011-12-19 03:31:23

回答

1

首先获取内容:

$content = file_get_contents('filename'); 

获取每一行:

$line = explode('\n', $contents); 

现在你有一个数组的每一行;遍历每个再次爆发,上逗号,并插入到DB

$ct = count($arr); 
while($i < $ct) 
{ 
    $arr = explode(',', $line[$i]); 
    /* Insert into database value $i, $arr[1], $arr[2], just ignore $arr[0] which contains your original string */ 
    $i++; 
} 
+0

照顾的数据实际上是不是在数据库中的文本文件,但 – bammab 2011-12-19 03:29:02

+0

@bammab查看编辑。 – check123 2011-12-19 03:33:23

+0

谢谢我改变了代码直接添加到数据库,你现在可以看看它吗? – bammab 2011-12-19 04:06:52

1

我想使数据库具有自动递增,所以你不必担心它的主键,但如果这是不可能的只是扔在一个for循环:

$array = explode("\n",file_get_contents("file.txt")); 
foreach($array as $count => $line) { 
    $array[$count] = str_replace('xxx',$count+1,$line); 
} 
+0

我做了改变,你现在可以看看。谢谢 – bammab 2011-12-19 04:07:14