0

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
include_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.

3
  • could you format your code , please? Select your code and press {} button to do so. Commented May 11, 2011 at 1:26
  • && $num<=$number why do you need this part? Commented May 11, 2011 at 1:26
  • can you do a var_dump($row) after the start of the while loop, and show us the output. Commented May 11, 2011 at 1:31

2 Answers 2

3

$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?

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, that works -- ignore my previous comment on the other post, my screen reader went to the wrong edit field :).
1

maybe try mysql_fetch_assoc($result) opposed to mysql_fetch_array($result)?

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.