Reputation: 1
I'm trying to get chat messages from my phpmyadmin database (it has 2 messages in it), but there is something wrong with my query. Here it is:
$query = "SELECT * FROM chat WHERE (user_from='". $_SESSION['username'] ."' AND user_to='". $result['username'] ."') OR (user_from='". $result['username'] ."' AND user_to='". $_SESSION['username'] ."') ORDER BY id DESC";
$chatlog = $db->query($query);
$message = $chatlog->fetch_array(MYSQLI_ASSOC);
When running this code: echo $message['message'];
only the first message shows up, I have also tried using foreach, but that didn't seem to work either.
Upvotes: 0
Views: 102
Reputation: 1
Thanks alot guys, it worked when using fetch_all here is my code now:
$query = "SELECT * FROM chat WHERE (user_from='". $_SESSION['username'] ."' AND user_to='". $result['username'] ."') OR (user_from='". $result['username'] ."' AND user_to='". $_SESSION['username'] ."') ORDER BY id DESC";
$chatlog = $db->query($query);
$message = $chatlog->fetch_all(MYSQLI_ASSOC);
foreach ($message as $chat) {
echo $chat['message'];
}
Upvotes: 0
Reputation: 60559
You only get back one message because thats what fetch_array
does - it gets the next record as an array.
If you want to get multiple records, you'll need to loop over the rows and call fetch_array
for each row:
while ($message = $chatlog->fetch_array(MYSQLI_ASSOC)) {
$messages[] = $message;
}
Also, used parameterized queries or prepared statements to save yourself from SQL injection
Upvotes: 2