Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can you add all the rows from a mysql_query to a mysql_fetch_array()? I want to be able to do it as efficiently as possible as it could be working with quite a few rows.

share|improve this question
    
I don't understand what you want to do. Please clarify your question. Do you want to sum certain row values? –  Felix Kling Jan 10 '11 at 3:01
    
What's wrong with the standard while ($row = mysql_fetch_assoc($result)) { echo $row['id']; }? –  thirtydot Jan 10 '11 at 3:03
    
Nope, just create a nested array with a mysql_query(). I guess mysql_fetch_array() only gets one row, and I need to get all of them. –  Kyle Hotchkiss Jan 10 '11 at 3:03

2 Answers 2

up vote 10 down vote accepted

The most common way:

$rows = array();

while(($row = mysql_fetch_array($result))) {
    $rows[] = $row;
}

as shown in the examples in the documentation.

share|improve this answer
1  
I couldn't bring myself to write this answer. –  thirtydot Jan 10 '11 at 3:06
    
There's a standard way? Well now I know, thanks Felix! –  Kyle Hotchkiss Jan 10 '11 at 3:07
    
@thirtydot: Sry ;) If you want to write it, I'll delete mine... –  Felix Kling Jan 10 '11 at 3:07
    
No no, it's just funny :D –  thirtydot Jan 10 '11 at 3:08
1  
lol a little heavy on the perenthesies –  Adelphia Nov 20 '12 at 9:19
<?php

$db = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306);

$startTime = microtime(true);

$result = $db->query("select * from users");

$users = $result->fetch_all(MYSQLI_ASSOC); // faster

// while($row = $result->fetch_assoc()) $users[] = $row; //slower

echo sprintf("%d users fetched in %s secs", 
    count($users), number_format(microtime(true) - $startTime, 6, ".", ""));

$db->close();

?>

EDIT some runtime stats

$users = $result->fetch_all()

  1000 users fetched in 0.001462 secs
  5000 users fetched in 0.005493 secs
 15000 users fetched in 0.015517 secs
 50000 users fetched in 0.051950 secs
100000 users fetched in 0.103647 secs

vs.

while($row = $result->fetch_assoc()) $users[] = $row; 

  1000 users fetched in 0.001945 secs
  5000 users fetched in 0.008101 secs
 15000 users fetched in 0.023481 secs
 50000 users fetched in 0.081441 secs
100000 users fetched in 0.163282 secs

interesting :)

share|improve this answer
1  
A better answer, if only because it avoids a "relatively slow" PHP while loop, which could matter slightly if there are 5 zillion rows. –  thirtydot Jan 10 '11 at 3:13
    
Your +1 is from me, ..interesting. –  thirtydot Jan 10 '11 at 5:13
    
lol - just a shame you're not the questioner asking about efficiency :P –  f00 Jan 10 '11 at 14:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.