I am querying a MySQL database through PHP. I read input from a file. Then loop over the inputs to query the database to retrieve 3 attributes for each input.
The database connection is fine. All the queries run fine otherwise. What is happening is for all the queries but the last one I get mysql_num_rows($result) = 0
. And only for the last one it prints correct results.
I cannot figure out why. What might possibly be wrong?
$fh = fopen($my_File, 'r');
$arr = explode("\n", fread($fh, filesize($my_File)));
fclose($fh);
foreach ($arr as $line) {
if ($line != "\n" || $line != "" || $line != NULL) {
$query = "SELECT id, name, status FROM table1 WHERE id='$line'";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num = mysql_num_rows($result);
if ($num == 0) {
echo "NULL Set<br/>";
} else {
echo "RESULT Set<br/>";
}
}
Is it possible that the lines in your file are terminated by "\\r\\n" rather than just "\\n"? If so, you'll have an extra "\\r" at the end of each element of $arr (except the last).
Try adding
$line = trim($line);
at the beginning of your foreach loop and see if it makes a difference.
Better yet, use fgets instead of fread.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.