简体   繁体   中英

mysql_fetch_assoc fetching only one record

I have an array with the result of a query:

.....some code.....
$result = mysql_query("SELECT * FROM vttest");
$row = mysql_fetch_assoc($result);
print_r($row);

But it only prints one record, I can't put $row in a loop because I will be working on sorting that variable later.

Array
(
    [id] => 3
    [rep] => Mike
    [name] => Joe
    [department] => Business
    [location] => Room 1
    [email] => xxxx@hotmail.com
    [phone] => 519-123-4567
    [type] => Visit
    [drink] => Coffee
    [notes] => Some notes
    [lastVisited] => 2010-08-27
    [nextVisit] => 2010-08-27
)

I know there are more records than that, how can I print all of it while still being able to work with the $row variable?

You are actually getting one record because you need to use a loop to get all records.:

$my_arary = array();
while($row = mysql_fetch_assoc($result)){
  $my_arary[] = $row;
  print_r($row);
}

As you said, later you can use the $my_arary to do whatever you like.

$result = mysql_query("SELECT * FROM vttest");

$data = array();
while($row = mysql_fetch_assoc($result)){
    array_push($data, $row);
}

You need to put it in a loop. And then, if you need to work on that variable later, use mysql_data_Seek to reset internal result pointer:

 mysql_data_seek($result, 0);
 // your later code.

You almost had it, you needed to use a loop to go though the results to get each row, and as you do so assign each row to a table.

The following with be something your be looking for.

$result = mysql_query("SELECT * FROM vttest");
while($row = mysql_fetch_assoc($result)){
    $rows[] = $row;
}

Then all you need to do to access that array is the following.

foreach($rows as $index => $value){
    print_r($value);
}

The foreach will print each row with in your array one at a time, letting you short or use that data as you wish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM