检索数据库记录集到PHP中的数组 [英] Retrieving a database record set into an array in php
问题描述
我想从一个MySQL表作为数组获取一组记录。
I want to retrieve a set of records from a MySQL table as an array.
到目前为止,我能够检索每一行作为关联数组。但我想在一个阵列中的所有行,因为我要访问的jQuery的完整的对象,以显示它们。
So far I was able to retrieve each row as an associative array. But I want all the rows in one array because I have to access that complete object in jQuery to display them.
这是我这样做far.This是我的.php脚本来检索数据。
This is what I have done so far.This is my .php script to retrieve data
//select query
$result = mysql_query("SELECT * FROM student",$con) or die (mysql_error());
$numRows = mysql_num_rows($result); //to iterate the for loop
//passing as an associative array
for ($count = 0; $count < $numRows; $count++){
$row = mysql_fetch_array($result, MYSQL_ASSOC);
echo json_encode($row);
}
这是我目前得到
{"StuId":"1","fName":"Saman","lName":"Kumara","age":"14","grade":"A"}
{"StuId":"2","fName":"Marry","lName":"Vass","age":"12","grade":"B"}
{"StuId":"3","fName":"Navjoth","lName":"Bogal","age":"32","grade":"A"}
{"StuId":"4","fName":"Jassu","lName":"Singh","age":"22","grade":"E"}
不过,我想这个结果集如下。
But I want this result set as follows.
[
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]
我在寻求这样的帮助。先谢谢了。
I seek help in doing this. Thanks in advance.
推荐答案
把它们都放在一个阵列,然后json_en code是:
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:没有必要计算结果循环的数量。 mysql_fetch_ *将在内部保持一个指向当前记录,并增加了在每次调用。这使得它一个完美的候选人在while循环的简单易用。此外,而不是mysql_fetch_array和传球MYSQL_ASSOC,你可以简单地使用mysql_fetch_assoc来代替,方法我更preFER。使得code更容易阅读过(在我看来,反正)。
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).
这篇关于检索数据库记录集到PHP中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!