2

I have written php script to read the content from text file and insert them into database. The text file have has just 3 entries but while loop is running 4 times. Don't know why??

Here, is the script

$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);

As the script is running one time extra, it inserts a row in table with just $id value and rest both fields empty. Thanks!!

2
  • What happens when you initialize your counter to 0 instead of 1? Commented Oct 19, 2012 at 22:39
  • 1
    Sure you dont have a newline at the end of the file? Commented Oct 19, 2012 at 22:40

1 Answer 1

1

fgets returns false if there's nothing to read, so check for it returning (===) false within your loop, or change your loop to this example from the documentation:

while (($buffer = fgets($handle, 4096)) !== false) {
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.