Retrieving a database record set into an array in php

后端 未结 1 725
鱼传尺愫
鱼传尺愫 2021-01-13 08:44

I want to retrieve a set of records from a MySQL table as an array.

So far I was able to retrieve each row as an associative array. But I want all the rows in one ar

相关标签:
1条回答
  • 2021-01-13 09:36

    Put it all in one array, then json_encode it:

    $json = array( );
    $result = mysql_query("SELECT * FROM student",$con) or die (mysql_error());
    while( $row = mysql_fetch_assoc( $result ) ) {
        $json[] = $row;
    }
    echo json_encode( $json );
    

    FYI: there's no need to count the number of results to loop. mysql_fetch_* will internally keep a pointer to the current record and increment that on each call. That makes it a perfect candidate to use in a simple while loop. Also, instead of mysql_fetch_array and passing MYSQL_ASSOC, you can simply use mysql_fetch_assoc instead, a method I much prefer. Makes the code easier to read too (in my opinion, anyway).

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