The test-json.php script retrieves data from the database and converts it into JSON format.
<?php
$conn = new mysqli("localhost", "root", "xxxx", "guestbook");
$result=$conn->query("select * From lyb limit 2");
echo '[';
$i=0;
while($row=$result->fetch_assoc()){ ?>
{title:"<?= $row['title'] ?>",
content:"<?= $row['content'] ?>",
author:"<?= $row['author'] ?>",
email:"<?= $row['email'] ?>",
ip:"<?= $row['ip'] ?>"}
<?php
if(
$result->num_rows!=++$i) echo ',';
}
echo ']'
?>
When running select * From lib limit 2
on my database, it fetches the following records:
title | content | author | email |ip
welcome1 | welcome1 | welcome1 | <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087f6d646b67656d39487c6765266b687964686c">[email protected]</a> |59.51.24.37
welcome2 | welcome2 | welcome2 | <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6611030a05090b03542612090b4805090b00070b09064e030f0d">[email protected]</a> |59.51.24.38
To execute the script, use
php -f /var/www/html/test-json.php
.
[ {title:"welcome1",
content:"welcome1",
author:"welcome1",
email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f186949d929e9c94c0b1859e9cdf8295979a">[email protected]</a>",
ip:"59.51.24.37"},
{title:"welcome2",
content:"welcome2",
author:"welcome2",
email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1d6c4cdc2ceccc493e1d5cecc91cec3cf">[email protected]</a>",
ip:"59.51.24.38"}]
The retrieved data in JSON format can be displayed in a table by using JavaScript for calling back.
Below is the HTML code to show the AJAX response in a table:
<script src="http://127.0.0.1/jquery-3.3.1.min.js"></script>
<h2 align="center">Ajax show data in table</h2>
<table>
<tbody id="disp">
<th>title</th>
<th>content</th>
<th>author</th>
<th>email</th>
<th>ip</th>
</tbody>
</table>
<script>
$(function(){
$.getJSON("test-json.php", function(data) {
$.each(data,function(i,item){
var tr = "<tr><td>" + item.title + "</td>" +
"<td>" + item.content + "</td>" +
"<td>" + item.author + "</td>" +
"<td>" + item.email + "</td>" +
"<td>" + item.ip + "</td></tr>"
$("#disp").append(tr);
});
});
});
</script>
After typing 127.0.0.1/test-json.html
, you may notice no data being generated on the webpage despite executing test-json.php
.
Expected output should look like this in the table:
Ajax show data in table
title content author email ip
welcome1 welcome1 welcome1 <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1067757c737f7d752150647f7d3e777b797d">[email protected]</a> 59.51.24.37
welcome2 welcome2 welcome2 <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0a7b5bcb3bfbdb5e290a4bfbdbe97bab6b4">[email protected]</a> 59.51.24.38