mysql_fetch_array add all rows?

后端 未结 2 1111
花落未央
花落未央 2020-12-03 20:25

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.

相关标签:
2条回答
  • 2020-12-03 20:43

    The most common way:

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

    as shown in the examples in the documentation.

    0 讨论(0)
  • 2020-12-03 20:51
    <?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 :)

    0 讨论(0)
提交回复
热议问题