mysql to json php code example

Example 1: php mysql row to json

$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

Example 2: how to insert json data into mysql using php

<?php 

$josndata = '{
"student":{ "name":"Harry", "country":"United State", "ContactNo":2545454 }
}';  

// Database connection
$conn = new mysqli('localhost', 'username', 'password', 'databasename');

// Insert data Query
$sql = "INSERT INTO student_table ( name, jsondata )
VALUES ('Harry', '$josndata')";

if ($conn->query($sql) === TRUE) {
  echo "Insert your JSON record successfully";
} 
?>

Tags:

Php Example