Wireless Army
This is a blog / tips and tricks website for web developers and security researchers.
follow us in feedly


mysql to json
by admin
 at 2018-10-07 19:27:00.

with this script we will convert mysql data to json. one of many use cases may be if you want to offer an offline app that does the same thing as the online one.

with pdo

<?php
//conection to mysql database
try {
  $dsn = 'mysql:host=localhost;dbname=test';
  $username = 'root';
  $password = 'pass';
  $options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
  ); 
  $dbh = new PDO($dsn, $username, $password, $options);
  $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}
//convertion
foreach($dbh->query("select * from aa") as $row) {
 $output[]=$row;
}
print(json_encode($output));
$dbh = null;
?>


and with normal sql query

<?php
//conection to mysql database
mysql_connect("localhost","root","pass");
mysql_select_db("test");
//convertion
$sql=mysql_query("select * from aa");
while($row=mysql_fetch_assoc($sql)){
$output[]=$row;
}
print(json_encode($output));
mysql_close();
?>