查询中的数组结果只显示一个结果?

时间:2013-06-05 14:32:38

标签: php mysql ajax

我正在使用Ajax请求将数据解析为jquery。唯一的问题是我的查询只显示一个结果! 我的查询有多个输出,只显示一个。

有人可以帮助我吗?

$query = "SELECT u.id, c.id, c.chatbox_id, c.subject FROM tbl_users u, tbl_chatbox c WHERE '".$user_id."' = c.id";
$rows = array();

if ($result = $mysqli->query($query)) {
    while ($row = mysqli_fetch_assoc($result)) {
        $id = $row['id'];
        $subject = $row['subject'];
        $chatbox_id = $row['chatbox_id'];
    }
    $array = array(
        "result" => "1",
        "id" => $id,
        "subject" => $subject,
        "chatbox_id" => $chatbox_id
        );

    echo json_encode($array);
}

3 个答案:

答案 0 :(得分:2)

尝试以下

$query = "SELECT u.id, c.id, c.chatbox_id, c.subject FROM tbl_users u, tbl_chatbox c WHERE '".$user_id."' = c.id";
$rows = array();

if ($result = $mysqli->query($query)) {
  while ($row = $result->fetch_assoc()) {
    $id = $row['id'];
    $subject = $row['subject'];
    $chatbox_id = $row['chatbox_id'];

    $array[] = array(
    "result" => "1",
    "id" => $id,
    "subject" => $subject,
    "chatbox_id" => $chatbox_id
    );
  }

  echo json_encode($array);
}

答案 1 :(得分:1)

你也可以尝试一下。

$query = "SELECT u.id, c.id, c.chatbox_id, c.subject FROM tbl_users u, tbl_chatbox c  WHERE '".$user_id."' = c.id";
$rows = array();

if ($result = $mysqli->query($query)) {
 $i=0;
 while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$subject = $row['subject'];
$chatbox_id = $row['chatbox_id'];

$array[$i] = array(
"result" => "1",
"id" => $id,
"subject" => $subject,
"chatbox_id" => $chatbox_id
);
$i++;

}

echo json_encode($ array); }

答案 2 :(得分:0)

首先,改变一下:

while ($row = mysqli_fetch_assoc($result)) {

到此:

while ($row = $result->fetch_assoc()) {

你正在混合使用mysqli的面向对象和程序样式,这可能会导致问题。 fetch_assoc documentation有更多信息。

然后,只需将$array作业放在 while循环中:

while ($row = $result->fetch_assoc()) {
    $array[] = array(
        "result" => "1",
        "id" => $row['id'],
        "subject" => $row['subject'],
        "chatbox_id" => $row['chatbox_id']
    );
}

在此while循环结束后,$array将是一个关联数组数组。您可以像这样使用它:

foreach($array as $db_row) {
    echo "This row's id is " . $db_row['id'] . '<br />';
    echo "This row's subject is " . $db_row['subject'] . '<br />';
}