Algernop K. Algernop K. - 3 months ago 20
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

$row1
,
$row2
, and
$row3
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
$row1
, but making the other two individual variables equal ex.nu and lol.de I can't.

id | url
---+------------
1 | www.hi.com //Save
2 | www.ex.nu //Save
3 | www.lol.de //Save
4 | www.mo.ae //Skip
//DB-setup


-

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]
}

echo
json_encode(array(
'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

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'];
}

echo 
  json_encode(array(
     'row1' => $row1,
     'row2' => $row2,
     'row3' => $row3
  ));