将mySQL数据库查询转换为PHP中的JSON
问题描述:
我正在使用以下代码连接到本地数据库并从表中查询结果。以下代码无法以JSON格式打印我的结果。有什么我失踪?谢谢你的帮助!将mySQL数据库查询转换为PHP中的JSON
<?php
if (!$link = mysql_connect('localhost', 'root', 'root')) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db('tm-charts', $link)) {
echo 'Could not select database';
exit;
}
$sql = 'SELECT Name,status FROM Estimates';
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
echo json_encode($rows);
?>
答
第二种可能性:某些单元格包含非法字符,然后
更正:您的评论表示您所得到的编码阵列,但是您没有收到它作为JSON,要解决这个问题,你必须首先设置标题:
header('Content-Type: application/json; charset=utf-8');
重要的是,在调用标题函数之前,您没有输出。不在PHP标签内的空行已经是一个输出(也在包含中)。
第二种可能性:某些单元格包含非法字符,然后
json_encode
失败。
+0
包括该代码以及使用:mysql_set_charset(“UTF8”,$ link);成功了! – Liz
http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – AbraCadaver
mysql_函数已被弃用,不应再使用。据说,我不能立即看到代码的问题。你有没有得到任何输出? var_dump($ rows);'给了什么? – rjdown
从浏览器运行此脚本。你在页面输出中看到JSON字符串吗? – RiggsFolly