从文件向数据库表添加条目

时间:2013-07-15 14:57:18

标签: php mysql

我正在尝试使用PHP脚本从文本文件向数据库表中添加条目。文本文件包含2000行,我希望每行都是数据库表中的一个条目。这是我的代码。它运行正常但没有添加到表中。

<?php

$link = new mysqli('xxx.xxx.xxx.xx', 'xxxxxx', 'xxxxxxxx', 'xxxxxxxxxxx');
 if ($link->connect_errno) {
    die('Failed to connect to MySQL: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
 }
 $filename = 'serials.txt';
 $file = file($filename);
 foreach($file as $line) {
   $result = $link->query("INSERT INTO mytable SET serial=$line");
 }
?>

1 个答案:

答案 0 :(得分:2)

  1. 打印错误消息
  2. escape数据
  3. <?php
    
    $link = new mysqli('xxx.xxx.xxx.xx', 'xxxxxx', 'xxxxxxxx', 'xxxxxxxxxxx');
     if ($link->connect_errno) {
        die('Failed to connect to MySQL: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
     }
     $filename = 'serials.txt';
     $file = file($filename);
     foreach($file as $line) {
       $result = $link->query("INSERT INTO mytable SET serial='"
                .$link->real_escape_string($line)."'");
       if($link->errno) echo($link->errno.": ".$link->error);
     }
    ?>