Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a simple mysql query checking the database table 'all_users' for an e-mail which was entered in a text field.

The e-mail is in a variable called $email.

In my test case, $email is [email protected] and that e-mail exists in the database table.

When I do this:

$result=mysql_query("select * from all_users where email='$email' ") or die (mysql_error());
$row=mysql_fetch_array($result);
$num=mysql_num_rows($result);

$num is zero even though $row is found.

So when I do echo $row['email']; it correctly prints out '[email protected]' but when I do echo $num; it's 0!

What am I doing wrong here? I've done this a thousand times but never had this issue.

share|improve this question
Really weird. Change your query to select * from all_users and update us with the result , please. – Ofir Baruch Mar 7 '12 at 11:47
up vote 2 down vote accepted

From http://php.net/manual/en/function.mysql-fetch-array.php - Returns an array that corresponds to the fetched row and moves the internal data pointer ahead

So change the order, i.e. first use mysql_num_rows and only then do mysql_fetch_array

share|improve this answer
Makes sense, but I've done it in this order before and it worked, even when there's only 1 row found. Anyway, thanks, works now. – jovan Mar 7 '12 at 11:52

If you reverse the order of the statements, it will work as you expect. You are retrieving the row from the resource before asking it how many rows it has left. Since you are evidently only finding one row, this results in 0, because you have already retrieved that row.

If you do this it should work:

$num = mysql_num_rows($result);
$row = mysql_fetch_array($result);
share|improve this answer
<?php
mysql_connect("localhost","root","");
mysql_select_db("task");
$q="SELECT * FROM category WHERE parent_category_id = '1'";
$v=mysql_query($q);
$row=mysql_fetch_array($v);
$frow=mysql_num_rows($v);
echo $frow;
?>
share|improve this answer
How's this better than the OP's code? – dotman14 Mar 7 '12 at 13:35
@dotman14, e.g. much faster than the OOP, however I don't know how correct this code is. – holex Jul 2 at 13:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.