R
R
Ruslan Website2020-05-14 17:26:19
MySQL
Ruslan Website, 2020-05-14 17:26:19

How to display a table from Mysql via json using a loop?

This code displays the table correctly, if you add a new row and reload the page, the table will also be updated and displayed with a new row.

$res2 = mysqli_query($conn, $sotr);

echo "<table class='table'><tr style='font-weight: bold;'><td>ФИО</td><td>Должность</td><td>Дата рождения</td><td>Мобильный номер</td><td>E-mail</td></tr>";

while ($rob = mysqli_fetch_row($res2)) {

echo "<tr><td>$rob[0]</td><td>$rob[1]</td><td>$rob[2]</td><td>$rob[3]</td><td>$rob[4]</td></tr>";

}

echo "</table>";


Made an ajax request on button click that adds a record to the database. In the same handler, a table is requested, and through json it correctly (without reloading the page) displays only the specified array of records in the form of a table.

$res = mysqli_query($conn, $sotr);

while ($rob = mysqli_fetch_array($res)) {

$tor[] = "<tr><td>$rob[0]</td><td>$rob[1]</td><td>$rob[2]</td><td>$rob[3]</td><td>$rob[4]</td></tr>";

}

echo json_encode("<table class='table'><tr style='font-weight: bold;'><td>ФИО</td><td>Должность</td><td>Дата рождения</td><td>Мобильный номер</td><td>E-mail</td></tr>$tor[0]$tor[1]$tor[2]$tor[3]$tor[4]$tor[5]$tor[6]$tor[7]$tor[8]</table>");


BUT, it is simply impossible to make it so that after pressing the button, through json, not only the lines specified in the array, but all the lines from the while loop are displayed. I add jason_encode to while
$res = mysqli_query($conn, $sotr);

while ($rob = mysqli_fetch_array($res)) {

$tor[] = "<tr><td>$rob[0]</td><td>$rob[1]</td><td>$rob[2]</td><td>$rob[3]</td><td>$rob[4]</td></tr>";

echo json_encode("<table class='table'><tr style='font-weight: bold;'><td>ФИО</td><td>Должность</td><td>Дата рождения</td><td>Мобильный номер</td><td>E-mail</td></tr>$tor[0]$tor[1]$tor[2]$tor[3]$tor[4]$tor[5]$tor[6]$tor[7]$tor[8]</table>");
}


in the console gives such an error 5ebd52ee1d82b341031721.png

json_encode works outside while, but does not work inside while.

Dear, please tell me, is it possible to implement such a function using php, json, javascript, html?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Gordinskiy, 2020-05-14
@Sadyrbaev

json_encode works outside of a while but doesn't work inside a while.

It works fine, but concatenating multiple Json strings will not give valid Json.
BUT, it's just not possible to do that.

Well, since it's impossible, what questions?
Use implode instead of manual enumeration. Or do not collect the array at all, but immediately concatenate into one string.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question