Retrieving a database record set into an array in php(将数据库记录集检索到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.
这是我到目前为止所做的.这是我检索数据的 .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_encode:
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 );
仅供参考:无需计算要循环的结果数.mysql_fetch_* 将在内部保留一个指向当前记录的指针,并在每次调用时增加它.这使它成为在简单的 while 循环中使用的完美候选者.此外,您可以简单地使用 mysql_fetch_assoc 代替 mysql_fetch_array 和传递 MYSQL_ASSOC,这是我更喜欢的一种方法.也使代码更易于阅读(在我看来,无论如何).
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中的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将数据库记录集检索到php中的数组中
基础教程推荐
- 在多维数组中查找最大值 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01