user780483
user780483

Reputation: 3063

Mysql database retrieve multiple rows

I use a mysql database. When I run my query I want to be able to put each row that is returned into a new variable. I dont know how to do this.

my current code:

<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");

$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{

$solution=$row['solution'];
}
?>

The thing is that check num rows can return a row of an integer 0-infinity. If there are more solutions in the database how can I assign them all a variable. The above code works fine for 1 solution, but what if there are more? Thanks.

Upvotes: 2

Views: 23842

Answers (2)

zlkn
zlkn

Reputation: 54

You can't give each variable a different name, but you can put them all in an array ... if you don't know how this works I suggest looking at a basic tutorial such as http://www.w3schools.com/php/php_arrays.asp as well as my code.

A very simple way (obviously I haven't included mysql_num_rows etc):

$solutions = array()

while($row = mysql_fetch_assoc($result)) {
  $solutions[] = $row['solution'];
}

If you have three in your result solutions will be:

$solutions[0] -> first result $solutions[1] -> second $solutions[2] -> third

Upvotes: 3

Nathan Romano
Nathan Romano

Reputation: 7096

 <?php
      $result=mysql_query("SELECT * FROM table WHERE var='$var'");
      $solution = array();

      $check_num_rows=mysql_num_rows($result);

      while ($row = mysql_fetch_assoc($result))
      {
           $solution[]=$row['solution'];
      }
 ?>

Upvotes: 0

Related Questions