Next element of array every iteration chat messages display php

229 views Asked by At

I want to display messages in my chatbox but my code displays only first row from database. I hope polish names of variables arent problem. Greets.

Chatbox:

phpmyadmin rows:

<?php 

//connecting to database
$connect = @mysqli_connect("localhost","root","","chat") or die ('nie udalo sie polaczyc do bazy danych');

//fetch messages

$zapytanie = mysqli_query($connect, "SELECT * FROM wiadomosci");

$wynik_zapytania = mysqli_fetch_array($zapytanie);
;
foreach ($zapytanie as $key) {

    $nazwa = $wynik_zapytania['nazwa'];
    $tresc = $wynik_zapytania['tresc'];
    $godzina = $wynik_zapytania['godzina'];


    echo("
        <li>
            <div class='chat-body clearfix'>
                <div class='header'>
                    <small class='text-muted'><span class='glyphicon glyphicon-time'></span>".$godzina."</small>
                    <strong class='pull-right primary-font'>".$nazwa."</strong>
                </div>
                <div class='tresc'>
                <p>
                    ".$tresc."
                </p>
                </div>
            </div>
        </li>
        ");
}

?>
2

There are 2 answers

0
NoLimes On
<?php
require_once "connect.php";

$zapytanie = mysqli_query($link, "SELECT id, nazwa, tresc, godzina FROM wiadomosci");

       while ($row = mysqli_fetch_array($zapytanie))
{
    $zapytanie_tablica[] = array('id'=>$row['id'], 'imie'=> $row['nazwa'], 'tekst'=> $row['tresc'], 'czas'=> $row['godzina']);
}
        ;
?>
<?php foreach($zapytanie_tablica as $key): ?>







                            <li>
                                <div class='chat-body clearfix'>
                                    <div class='header'>
                                        <small class='text-muted'><span class='glyphicon glyphicon-time'></span></small>
                                        <strong class='pull-right primary-font'><?php  echo htmlspecialchars($key['imie'], ENT_QUOTES, 'UTF-8'); ?></strong>
                                    </div>
                                    <div class='tresc'>
                                    <p>
                                        <?php  echo htmlspecialchars($key['tekst'], ENT_QUOTES, 'UTF-8'); ?>
                                    </p>
                                 </div>
                                </div>
                            </li>

<?php endforeach; ?>

It working. I tested this on my XAMPP server.

0
someOne On

You need to use a loop, to fetch all the returned rows, like the following:

while($wynik_zapytania = mysqli_fetch_array($zapytanie)) {
    // the rest of your code...

(Don't forget to add the corresponding } in the appropriate place :)