How to fetch data from database using json decode in php and display the result like below?

570 views Asked by At

I used JSON to send value from form to database. My table (name of the table tblstudent) has three columns i.e.

    name                   score                               pic

["aa","bb","cc"]     ["525","523","562"]         ["img1.png","img2.png","img3.png"]

How to get values from JSON encode and put it into foreach loop to get the result like

img1.png
aa
525

image2.png
bb
523

image3.png
cc
562

and so on

2

There are 2 answers

0
Jerson On BEST ANSWER

You can use for loop and set index by the key

  $name = ["aa","bb","cc"];
  $score = ["525","523","562"];
  $pic =  ["img1.png","img2.png","img3.png"];

  for($i = 0; $i < count($pic); $i++) {

    echo $pic[$i] . PHP_EOL;
    echo $name[$i] . PHP_EOL;
    echo $score[$i] . PHP_EOL;
    echo PHP_EOL;

  }

Output with :

img1.png
aa
525

img2.png
bb
523

img3.png
cc
562
0
Viral Ghodadara On

I have a try to index.php file send post request to request.php and request.php file send data to form of json_decode and print data to file.

index.php

<!DOCTYPE html>
<html>
<head>
    <title>send request</title>
    <!--- jQuery cdn ----->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <div class="display-data"></div>
</body>
</html>
<script type='text/javascript'>
    
    $(document).ready(function () {
        $.post('request.php', function (data, status) {
            if (status == 'success') {
                $('.display-data').append(data);
            }
        })
    });
    
</script>

request.php

<?php

//This is a create a connection 
$servername = 'localhost';
$dbname = "stackoverflow";  
$username = "root";
$pass = "";

$conn = new PDO("mysql:host=$servername; dbname=$dbname;", "$username", "$pass");

//This is a create a connection end


$selectSql = "SELECT * FROM tblstudent";
$select = $conn->prepare($selectSql);
$select->execute();

for($i=0; $i<3; $i++) {
    $data = $select->fetch();
    
    $img[] = $data['image']; //This is a array of image
    $name[] = $data['name']; //This is a array of name
    $score[] = $data['score']; //This is a array of score
}

for($i=0; $i<3; $i++) {
    
    echo $img[$i]."<br>"; //Print data to index.php file
    echo $name[$i].'<br>'; //Print data to index.php file
    echo $score[$i]."<br>"; //Print data to index.php file
    echo '<br><br>';
}

?>