php只从数据库返回1行

时间:2018-03-02 11:57:36

标签: php

我有以下php代码(在文件returndata.php中)来检索用户的消息:

$sql = 'SELECT * FROM usertimes WHERE receiver ="'. $messagesforaccount. '"';

$result = $conn->query($sql);
$response = array();

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $response['message'] = $row["message"];
        $response['date'] = $row["date"];
        $response['sender'] = $row["sender"];
        $response['receiver'] = $row["receiver"];
    }
    echo json_encode($response);
} else {
    echo "  0 results";
}

然后javascript如下(在网页上显示消息及其中的一些信息,如发件人,日期等):

$.post(
          "returndata.php",
          { messagesforaccount: userAccount },
          function(response) {
              var sender = response.sender;
              var receiver = response.receiver;
              var message = response.message;
              var date = response.date;

              console.log('Retreived data: ', sender, receiver, message, date);

              p = document.createElement('p')
              p.innerHTML = message + '<br>' + 'sent by ' + sender + ' at ' + date
              listmessages.appendChild(p)

          }, 'json'
      );

这只会向页面添加一条消息(数据库中的最后一条消息)。什么应该是php所以它循环遍历所有结果,并为每个结果它将消息添加到网页?

2 个答案:

答案 0 :(得分:0)

您需要在这样的数组中回复所有这些:

$sql = 'SELECT `message`, `date`, `sender`, `receiver` FROM `usertimes` WHERE `receiver` ="'. $messagesforaccount. '"';

您应该只请求您需要的字段。这提高了性能并减少了开销。稍后,您可以将整行推送到响应中。

$result = $conn->query($sql);
$response = array();

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $response[] = $row;
    }
    echo json_encode($response);
} else {
    echo "  0 results";
}

答案 1 :(得分:0)

你在那里犯了一点错误。如果你想要多个数据的关联数组,那么你应该有一个二维数组,你必须有一个第二维数组的索引

  <?php
$sql = 'SELECT * FROM usertimes WHERE receiver ="'. $messagesforaccount. '"';

$result = $conn->query($sql);
$response = array();
$index = 0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[$index]['message'] = $row["message"];
$response[$index]['date'] = $row["date"];
$response[$index]['sender'] = $row["sender"];
$response[$index]['receiver'] = $row["receiver"];

$index++;//incrementing index variable
}
echo json_encode($response);
} else {
echo "  0 results";
}

?>

作为回报,你可以用这种方式迭代那个数组

  for ($i=0;$i<count($response);$i++)

{
    echo $response[$i]['message'] . "<br>" ;
    echo $response[$i]['date'] . "<br>" ;
    echo $response[$i]['sender'] . "<br>" ;
    echo $response[$i]['receiver'] . "<br>" ;

}