php错误 - 循环运行一次额外?

时间:2012-10-19 22:35:08

标签: php mysql

我编写了php脚本来读取文本文件中的内容并将其插入数据库。文本文件只有3个条目,但循环运行4次。不知道为什么??

这里是脚本

$con = mysql_connect("localhost","root","root") or die("Could not connect to server");
$db = mysql_select_db("bolly_songs",$con) or die("Could not select database");

$file1 = "ex_name.txt";
$file2 = "ex_link.txt";

$fp1 = fopen($file1,"r");
$fp2 = fopen($file2,"r");

$ctr =1 ;

while(!feof($fp1)){
    $text1 = fgets($fp1);
    $text2 = fgets($fp2);

    $id = "emov".$ctr;

    $query = "insert into example_table(movie_name, movie_link,movie_id) values('$text1', '$text2','$id')";

    $result = mysql_query($query) or die("Query failed ".mysql_error());

    echo "Data inserted in field $ctr with id as $id \n";
    $ctr++;
}

fclose($fp1);
fclose($fp2);

当脚本运行一次额外的时候,它会在表中插入一行只有$ id值并将两个字段都清空。 谢谢!

1 个答案:

答案 0 :(得分:1)

如果没有什么可读的话,

fgets会返回false,所以检查它在循环中返回(===)false,或者从文档中将循环更改为此示例:

while (($buffer = fgets($handle, 4096)) !== false) {
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}