在 Mysqli 准备语句上获取 json_encode() 时出现问题
Having Issue on Getting json_encode() On Mysqli Prepared Statement
我在使用 MySQLi 导出准备语句的结果时遇到一些问题。
$age = "young";
$rows = array();
$mysqli = new mysqli($db_hostname, $db_username, $db_password, $db_database);
$stmt = $mysqli->prepare("SELECT fname, lname FROM users WHERE age=?");
$stmt->bind_param('s', $age);
$stmt->execute();
$stmt->bind_result($thefName,$thelName);
while($stmt->fetch())
{
array_push($rows, $thefName,$thelName);
}
$stmt->close();
$mysqli->close();
echo json_encode($rows);
如您所见,我正在尝试将 json_encode($rows);
每一行回显为 JSON 数组,如下所示:
[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
但我得到的是
["John", "Doe", "Anna", "Smith", "Peter", "Jones"]
能否请您告诉我为什么会发生这种情况以及我该如何解决
推送正确的数组 -
array_push($rows, array('firstName' => $thefName, 'lastName' => $thelName));
我在使用 MySQLi 导出准备语句的结果时遇到一些问题。
$age = "young";
$rows = array();
$mysqli = new mysqli($db_hostname, $db_username, $db_password, $db_database);
$stmt = $mysqli->prepare("SELECT fname, lname FROM users WHERE age=?");
$stmt->bind_param('s', $age);
$stmt->execute();
$stmt->bind_result($thefName,$thelName);
while($stmt->fetch())
{
array_push($rows, $thefName,$thelName);
}
$stmt->close();
$mysqli->close();
echo json_encode($rows);
如您所见,我正在尝试将 json_encode($rows);
每一行回显为 JSON 数组,如下所示:
[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
但我得到的是
["John", "Doe", "Anna", "Smith", "Peter", "Jones"]
能否请您告诉我为什么会发生这种情况以及我该如何解决
推送正确的数组 -
array_push($rows, array('firstName' => $thefName, 'lastName' => $thelName));