Skip to content

Instantly share code, notes, and snippets.

@Mauryashubham
Created October 9, 2019 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mauryashubham/2c07ebb08dea9a4b40826c1c85fdf55d to your computer and use it in GitHub Desktop.
Save Mauryashubham/2c07ebb08dea9a4b40826c1c85fdf55d to your computer and use it in GitHub Desktop.
Convert Mysqli Data Into JSON Format Using PDO
Convert Mysqli Data Into JSON Format Using PDO
/**
@author : Shubham Maurya,
Email id : maurya.shubham5@gmail.com
**/
Hi all , Welcome to shubhammaurya.com , Today we are going to discuss ,
Convert Mysqli Data Into JSON Format Using PDO
In this,we are going to use PDO .
 LET START
Convert Mysqli Data Into JSON Format Using PDO
So, To start first make a file in notepad and save it as jsonApi.php and paste the below code.
(Displaying data into json format)
<?php
$DB_host = "localhost";
$DB_name = "Your Database Name";
$DB_user = "Your Database User";
$DB_pass = "Your Database Password";
try{$conn = new PDO("mysql:host={$DB_host};dbname={$DB_name};charset=utf8",$DB_user,$DB_pass); }
catch(PDOException $e) {echo 'ERROR: ' . $e->getMessage(); }
$stmt = $conn->prepare("SELECT post_title FROM wp_posts ORDER BY ID DESC LIMIT 10");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$final=json_encode($results);
echo json_encode($results);
?>
Now,make a file in notepad and save it as jsonGet.php and paste the below code.
(Display Data Using JSON)
<?php
$burl="https://shubhammaurya.com/ajax/jsonApi.php";
$json = file_get_contents($burl);
$json_data=json_decode($json,true);
// $post_title=$json_data['post_title'];
foreach ($json_data as $value_m) {echo $value_m['post_title']."<br>";}
?>
[/php]
Comment Below, If any problem occurs.
STAY CONNECTED FOR MORE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment