我正在尝试从返回多行的mysql查询中提取数据。代码目前编码为只处理一行。 如何将多行数据保存到对象Date的实例变量中?
<?php
session_start();
require 'database.php';
class Date {
private $id = '';
private $titl = '';
private $tim = '';
private $dat = '';
private $usern = '';
}
if ($_SESSION['loginstatus']!=1){
die;
}
$username=$_SESSION['username'];
$date=$_POST['dateChosen'];
$stmt = $mysqli ->prepare("select ID, title, time from events where date=? and creator=?");
if (!$stmt){
$error = $mysqli->error;
$string="Query Prep Failed:" . $error;
echo json_encode(array(
"message"=> $string));
exit;
}
$stmt -> bind_param('ss',$date,$username);
$stmt -> execute();
$stmt ->bind_result($ID, $title,$time);
$count = 0;
while ($stmt->fetch()){
$count += 1;
echo json_encode(array("id"=>$ID,
"title"=> $title, "time"=>$time));
}
if ($count == 0){
echo json_encode(array(
"title"=> "NOT SET", "time"=>"NOT SET"));
}
$stmt->close();
header("Content-Type: application/json");
?>
答案 0 :(得分:1)
您正在创建多个单独/独立的JSON字符串,这是不正确的。您需要在循环中构建一个数组,然后在循环完成后对数组ONCE进行编码。
e.g。
$data = array();
while($stmt->fetch()) {
$data[] = array('id' => $ID, 'title' => etc....);
}
echo json_encode($data);
现在你正在制作
{"id":1,"title":"foo",...}{"id":2,"title":"bar",...}{etc...}
这是一个语法错误。它应该是
[{"id":1,"title":"foo",...},{"id":2,"title":"bar",...},{etc...}]
答案 1 :(得分:0)
更改你的while循环:
while($res = $stmt->fetch())
{
//do whatever, data is in the $res variable
}