Algernop K. Algernop K. - 11 months ago 49
SQL Question

Save the first three results in a while loop with given variable names?

I wanna save the first three results from my SQL-query in the variables

, and
and return them to ajax. The SQL-query sorts the order so that the first three looped will be the ones I wanna save.

Thing is, I can only figure out how to save one of them in
, but making the other two individual variables equal and I can't.

id | url
1 | //Save
2 | //Save
3 | //Save
4 | //Skip


while ($row = mysqli_fetch_array($result)) {
$row1 = $row['url']; //Works
//$row2 = $row['url']; Second result, tried using [1]
//$row3 = $row['url']; Third result, tried using [2]

'row1' => $row1,
'row2' => $row2,
'row3' => $row3

Simply, collect the first three items and save them in the given variables. Is there a simple solution to doing this?

Any help/tips/links will be much appreciated.

Answer Source

If you want to store them to $row1, $row2, $row3 you need to use variable variables. Try the below:

$query = "select * from url_list order by url asc limit 3";
$result = mysql_query($query);
$i = 1;
while ($data = mysql_fetch_array($result)) {
   $variable = 'row'.$i++;
   $$variable = $data['url'];

     'row1' => $row1,
     'row2' => $row2,
     'row3' => $row3