mysql_fetch_array returns nothing while mysql_num_rows returns 4 in php
I have some code in php that accesses a mysql database in sorted order, then prints out the info in a table. However, whenever it calls mysql_fetch_array, the function returns nothing, even though mysql_num_rows is 4. That is, if I do $row=mysql_fetch_array($result);, $row['name'] is "" even though there is most certainly a name column in the table. A snippet of the code is below:
<?php
incl开发者_如何转开发ude_once("include.php");
$number=0;
if(!isset($_GET['scores'])) {
$number=10;
}
else if((int )$_GET['scores']>100) {
$number=100;
}
else if((int) $_GET['scores']<0) {
$number=10;
}
else {
$number=(int) $_GET['scores'];
}
$con=mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname, $con);
$result=mysql_query("SELECT * FROM ".$dbtable_scores." ORDER BY score DESC,date;", $con);
$num=1;
echo("<table>");
echo("<tr><td>position</td><td>Name</td><td>score</td><td>date</td></tr>");
while($row=mysql_fetch_array($result) && $num<=$number) {
echo("<tr>");
echo("<td>".$num."</td>");
echo("<td>".$row['name']."</td><td>".$row['score']."</td><td>".$row['date']."</td>");
echo("</tr>");
$num++;
}
echo("</table>");
mysql_close($con);
?>
I have checked the query in mysql cli, and it seems to work fine. However, as you will see if you go to http://mtgames.org/index.php, the table has only the numbers that are not generated from mysql. The mysql table has columns name, score, date, among others. Any help is appreciated. Thanks, -Michael.
$row
is not being set to the result of mysql_fetch_array()
, it's being set to mysql_fetch_array() && $num <= $number
, which is probably equal to true
. It might work if you put some parentheses around ($row = mysql_fetch_array($result))
but you could save yourself some heartache by moving the && to an if statement that wraps the contents of the while.
A look at http://php.net/manual/en/language.operators.precedence.php confirms this. &&
has higher operator precedence than assignment, =
. However, and
has lower precedence. I never knew that! Why, oh why, php?
maybe try mysql_fetch_assoc($result)
opposed to mysql_fetch_array($result)
?
精彩评论