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
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);
?>
Output like :
[{“post_title”:”Auto Draft”},{“post_title”:”Top 10 Websites For Interview Preparation”},{“post_title”:”top 10 websites for interview preparation”},{“post_title”:”Top 10 Websites For Interview Preparation”},{“post_title”:”Top 10 Websites For Interview Preparation”},{“post_title”:”Top 10 Websites For Interview Preparation”},{“post_title”:”Top 10 Sites for your career in 2019″},{“post_title”:”Top 10 Tech Skills in demand in 2019″},{“post_title”:”Top 10 Tech Skills in demand in 2019″},{“post_title”:”Top 10 Tech Skills in demand in 2019″}]
Now,make a file in notepad and save it as jsonGet.php and paste the below code.
<?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']."
";}
?>
Output Like :
Auto Draft
Top 10 Websites For Interview Preparation
top 10 websites for interview preparation
Top 10 Websites For Interview Preparation
Top 10 Websites For Interview Preparation
Top 10 Websites For Interview Preparation
Top 10 Sites for your career in 2019
Top 10 Tech Skills in demand in 2019
Top 10 Tech Skills in demand in 2019
Top 10 Tech Skills in demand in 2019
Find Code at github : click here
Find More Codes : click here
Comment Below, If any problem occurs.
STAY CONNECTED FOR MORE
Awesome post! Keep up the great work! ЁЯЩВ
Great content! Super high-quality! Keep it up! ЁЯЩВ
Wow, lovely portal. Thnx …