我已经将以下PHP脚本连接到MySQL数据库,但它失败了:
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get a author from authors table
$result = mysql_query("SELECT authorid, name, biography FROM author WHERE authorid = 3");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
// success
$response["success"] = 1;
$result = mysql_fetch_array($result);
$author = array();
$author["authorid"] = $result["authorid"];
$author["name"] = $result["name"];
$author["biography"] = $result["biography"];
// user node
$response["author"] = array();
array_push($response["author"], $author);
// echoing JSON response
echo json_encode($response);
} else {
// no author found
$response["success"] = 0;
$response["message"] = "No author found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no author found
$response["success"] = 0;
$response["message"] = "No author found";
// echo no users JSON
echo json_encode($response);
}程序获得了结果,但是在代码行array_push($response"author",$author);(我设法使用echo获得了结果,但是程序实际上似乎没有报告任何错误)。如果我从查询中删除传记字段(这是一个文本字段),或者删除传记“biography”=$result“$author”行;程序将返回工作。因此,我认为这可能是由错误/空传记返回引起的,但我不明白为什么它应该返回,因为如果查询在数据库中运行,则会显示正确的结果,传记不为空。
这是从查询中删除履历字段时返回的响应:
{"success":1,"author":[{"authorid":"3","name":"Jane Austen","biography":null}]}你认为这个问题是如何产生的,我该如何解决它?
谢谢
编辑:根据Ben Harris的建议更改:
$result = mysql_fetch_array($result);
$response["author"] = [
"authorid" => $result["authorid"],
"name" => $result["name"],
"biography" => $result["biography"]
];
var_dump($response);
// echoing JSON response
echo json_encode($response);Var_dump打印正确
array(2) {
["success"]=> int(1)
["author"]=> array(3) {
["authorid"]=> string(1) "3"
["name"]=> string(11) "Jane Austen"
["biography"]=> string(41) "Jane Austen (1775 � 1817) was an English "
}
}然而,它仍然没有任何回声。知道为什么吗?
发布于 2018-01-27 08:05:19
问题是数据库没有使用utf8排序规则。感谢@RiggsFolly和@BenHarris在评论中的建议!非常感谢。
发布于 2018-01-26 05:49:14
您不需要创建中间数组,甚至不需要使用array_push。试一试,如果看不到预期的效果,可以使用print_r或var_dump进行调试。
$response["author"] = [
"authorid" => $result["authorid"],
"name" => $result["name"],
"biography" => $result["biography"]
];https://stackoverflow.com/questions/48452335
复制相似问题