Monday, June 27, 2011

PHP - Assign variable names to array elements from mysql query

It is useful to be able to take the results of a MYSQL query and assign variable names to the results, so that they can be used later on in a script.

This can be done simply as follows...


$result= mysql_query("SELECT id FROM table WHERE num='567' LIMIT 3") or die(mysql_error());

while ($row = mysql_fetch_array($result)) {

$ids[] = $row['id'];

}
$id1 = $ids[0];
$id2 = $ids[1]
$id3 = $ids[2];


So you now have 3 variables fetched from the mysql array that can be used outside of a loop.

This specific example limits the mysql result to 3. However you could do this for any (change the 3 to how many results you want) and unknown numbers of results doing a COUNT of returned results and then iterating based on that number.

No comments: