i allways end up doing this
$q = "select whatIwant FROM table where id = 'myId'";
$r = mysql_query($q);
while($i = mysql_fetch_array($r){
/* iterate just one withem */
$j = $i['whatIwant'];
}
echo $j;
how is this usually done? (i just want to avoid the unecessary loop)
In addition to the correct answers, there are multiple ways to handle this:
If you add
LIMIT 1, the result set will only contain one row and thewhileloop will terminate after one iteration:If you call
mysql_fetch_arraywithout a loop, you will get the first row of the result set:If you add
breakto the loop body, the loop will terminate after one iteration.You can also combine these approaches (although using
breakis not really elegant in this case).The best approach is using
LIMITand omitting thewhileloop, as @zaf shows in his answer. This makes the code clearer and avoids unnecessary operations in the database.