从PHP到MySQL到JSON [英] MySQL to JSON in PHP
本文介绍了从PHP到MySQL到JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个基本的MySQL数据库表People
,其中有3列(ID, Name, Distance
)
I have a basic MySQL database table People
with 3 columns (ID, Name, Distance
)
我正在尝试使用PHP将其作为JSON输出,以便我的Web应用程序可以接收它.我尝试使用另一个答案中的解决方案:
I am trying to output this with PHP as a JSON so my web app can pick it up. I tried using the solution from another answer:
$sth = mysql_query($con,"SELECT * FROM People");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
但是我只是返回一个空白数组[]
.
However I am just returning a blank array of []
.
更新:更改为mysqli并添加了转储:
Update: Changed to mysqli and added dumps:
$sth = mysqli_query("SELECT * FROM Events",$con);
$rows = array();
var_dump($sth);
while($r = mysqli_fetch_assoc($sth)) {
var_dump($rows);
$rows[] = $r;
}
print json_encode($rows);
返回:
NULL []
推荐答案
在mysql_query语句中交换查询和连接:
Swap your query and connection in the mysql_query-statement:
$sth = mysql_query("SELECT * FROM People", $con);
此外,不建议使用mysql-library.如果要编写新代码,请考虑使用mysqli_或PDO.
Besides that, the mysql-library is deprecated. If you're writing new code consider using mysqli_ or PDO.
这篇关于从PHP到MySQL到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文