【问题标题】:php mysql query returns multiple rows, save data to objectphp mysql查询返回多行,将数据保存到对象
【发布时间】:2015-07-16 17:11:48
【问题描述】:

我正在尝试从返回多行的 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");
?>

【问题讨论】:

    标签: php mysql sql row


    【解决方案1】:

    您正在创建多个单独/独立的 JSON 字符串,这是不正确的。您需要在循环中构建一个数组,然后在循环完成后对数组进行一次编码。

    例如

    $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...}]
    

    【讨论】:

      【解决方案2】:

      改变你的while循环:

      while($res = $stmt->fetch())
      {
          //do whatever, data is in the $res variable
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-18
        • 1970-01-01
        • 1970-01-01
        • 2015-03-17
        • 2020-06-26
        • 2013-12-01
        相关资源
        最近更新 更多