2

我已经编写了 php 脚本来从文本文件中读取内容并将它们插入数据库。文本文件只有 3 个条目,但 while 循环运行了 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 值,并将两个字段都保留为空。谢谢!!

4

1 回答 1

1

fgets如果没有可读取的内容,则返回 false,因此请检查它是否在循环中返回 (===) false,或者将循环更改为文档中的此示例:

while (($buffer = fgets($handle, 4096)) !== false) {
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
于 2012-10-19T22:40:08.670 回答