cheesycoder
cheesycoder

Reputation: 93

Displaying JSON data created using PHP and MySQL

I have a form on an HTML page which posts a user input to a PHP which executes a SQL statement to get information from a database and output it in JSON. Here is my PHP code to get the JSON data:

<?php

header('Content-type:application/json');

$con = mysqli_connect('localhost','root','','dbname');

if(isset($_POST['submit'])) 
    {
        $artist = $_POST['artist'];           

        $select = mysqli_query($con, "SELECT * FROM tblname WHERE artistName = ". $artist);

        $rows = array();

        while($row = mysqli_fetch_array($select))
        {
            $rows[] = $row;
        }

        echo json_encode($rows);
};

?>

When I submit the form on the HTML page, it goes to the PHP page and I get this result:

[{"0":"6","id":"6","1":"OASIS","artistName":"OASIS","2":"SOME MIGHT SAY","songTitle":"SOME MIGHT SAY","3":"1995-05-06","dateNo1":"1995-05-06"}]

(Code and JSON result have been simplified for this question)

Instead of going to this page, I'd like the data to be displayed nicely on the HTML page so that a user does not see this array. I'm not sure how to do this, any help?

Thank you!

Upvotes: 0

Views: 951

Answers (2)

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27192

There are two ways to solve this problem :

  1. Perform AJAX call from Javascript to PHP Page and parse the success response in to the HTML.

enter image description here

  1. Simply echo the values in PHP Page or add HTML itself in PHP Page as suggested by Tim.

Upvotes: 0

Tim
Tim

Reputation: 485

If you want the output formatted nicely, why are you encoding in JSON? JSON, although human-readable, isn't intended to be rendered on-screen as an end product.

I'd recommend looping through the $rows array and building a simple HTML table. You could, of course, wrap the data in any markup you like and even add CSS to style it as you see fit. Here's an example to get you started:

echo "<table>";
foreach($rows as $row) {
  foreach($row as $key => $value) {
    echo "<tr>";
    echo "<td>";
    echo $key;
    echo "</td>";
    echo "<td>";
    echo $value;
    echo "</td>";
    echo "</tr>";
 }
}
echo "</table>";

If you only want some of the data rendered, you can simply echo those values:

  foreach($rows as $row) {
  {
    echo "Artist:" . $row['artistName'];
    echo "<br>";
    echo "Song Title:" . $row['songTitle'];
    echo "<br>";
    echo "Date:" . $row['dateNo1'];
  }

Upvotes: 1

Related Questions