0

I have a mysql query:

$a=mysql_query("SELECT id FROM table1 WHERE p2='fruit' LIMIT 1");

This will only ever return one result or none.

I'm trying to first count the results, then if it 1, to pass the returned id to a variable.

Question: If I do $results=count(mysql_fetch_assoc($a)); to count the number of rows returned, can I still do later

while($row = mysql_fetch_array($a)){
    $id=$row['id'];
 }

or will the first delete the array somehow???

Is their a better way to do all this?

6 Answers 6

2

You really not need to do anything if there is one row or null Consider below code it will set id value if there is 1 row fetched otherwise it will be null

$id=''
while($row = mysql_fetch_array($a)){
    $id=$row['id'];
 }

No count needed.

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

Comments

2
$results=count(mysql_fetch_assoc($a));

does not count the number of rows as mysql_fetch_assoc returns one row. I believe you're looking for mysql_num_rows:

$results = mysql_num_rows($a);

Comments

1
$num_rows = mysql_num_rows($a);

You can then do an IF statement on this and later do a while loop on the fetched array

Comments

1

Have you tried mysql_num_rows ??

http://php.net/manual/en/function.mysql-num-rows.php

Comments

0

What happens when using:

while($row = mysql_fetch_array($a)){
    $id=$row['id'];
}

it is just like reading a file,every time mysql_fetch_array($a) is called the next line is parsed untill it reaches the end of the file. A cursor of some sort is known in the background. Meaning that if you would enter by hand //backgroundCursor = 0 $row = mysql_fetch_array($a) //backgroundCursor = 1 $row = mysql_fetch_array($a) //backgroundCursor =2 $row = mysql_fetch_array($a) //backgroundCursor = 3

The while instruction just automates the stuff. mysql_fetch_array increases the background cursor at every call so if you call it twice it will not give you the same line.

To get a clear view on this read something about reading from a file line by line.

Comments

0

No you cannot as each call to mysql_fetch_assoc() loads a new row, if there is any. You could indeed assign both variables at once:

$results=count($row = mysql_fetch_assoc($a));

but

But mysql_fetch_assoc($a)) returns false and as the result of count(false) is 1 this will not tell you anything. Besides, if there is no row all you really need is $row = mysql_fetch_assoc($a) and test if ($row) {...}.

1 Comment

No, count($row = mysql_fetch_assoc($a)) doesn't do what you think it does, because $row is not an array of rows, but just a row.

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.