1

If I only have one row that I'm getting through

$sql = mysql_query("SELECT id,user,comments FROM user WHERE id='15' AND user = '15'");

is there a way to just get the comments from that one row without going through a while loop :

while($row = mysql_fetch_array($sql)){
$comments = $row['comments'];
}

Is there something similar besides using a while loop? If my data has thousands to millions of data, a while loop will take a long time? Is this a more logical way to locate a certain row and reduce its speed?

Thanks for your help!

3 Answers 3

4

If you're only returning one row then only fetch once.

if ($row = mysql_fetch_array($result))
{
  $comments = $row['comments'];
}
Sign up to request clarification or add additional context in comments.

Comments

1
$sql = mysql_query("
SELECT id,user,comments 
FROM user 
WHERE id='15' 
AND user = '15' 
LIMIT 1");

The LIMIT 1 will stop the query after the first result

3 Comments

And what about fetching the results?
you can still use while, or if as Ignacio suggested, either will test for a result first. if you're not going to use an } else { condition (to handle what happens when no records are returned), you could just use $row = mysql_fetch_array($result); on it's own.
but the performance issue was handled via LIMIT 1, and it doesn't really matter how you access the data.
0

when you have more than one rows in resultset, then and then only you need to do it in loop else to fetch single row you are not required to put result set in loop.

you can do it like this..

if(mysql_num_rows($result) == 1){
   if($row = mysql_fetch_array($result)){
       $comments = $row['comments']; 
   }
}

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.