Reputation: 2281
I'm using this code below to convert database to JSON.
<?php
header('Content-type:application/json');
mysql_connect('localhost','root','')or die('cannot connect');
mysql_select_db('sanpham');
$sql = "SELECT * FROM cpu";
$result = mysql_query($sql);
if(!$result)
{
echo 'Lỗi SQL: '.mysql_error();
echo "\r\n<br />";
echo 'SQL: '.$sql;
exit;
}
$rows = array();
while($row=mysql_fetch_array($result)){
$rows[]=$row;
}
echo json_encode($rows);
?>
In my PHP file no error, no database, nothing display.
Upvotes: 1
Views: 13529
Reputation: 4772
Deprecated : mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in
As the warning suggest use either pdo or mysqli.
mysqli :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sanpham";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset('utf8');
$sql = "SELECT * FROM cpu";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rows = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($rows);
} else {
echo "no results found";
}
PDO :
<?php
$host = 'localhost';
$db = 'sanpham';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $user, $pass, $opt);
$result = $dbh->query("SELECT * FROM cpu");
$rows = $result->fetchAll();
echo json_encode($rows);
Upvotes: 8
Reputation: 585
Use this,
<?php
//open connection to mysql db
$connection = mysqli_connect("hostname","username","password","dbname") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from tablename";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
Upvotes: -1
Reputation: 988
You can simply use the json_encode method on an array storing the data of your mysql database ex:
<?php
$host = "localhost";
$db = "psychocodes";
$user = "your username"; //enter your database username
$pass = "your password"; //enter your database password
$conn = new mysqli($host,$user,$pass,$db);
$rows = array();
$sql = "SELECT * FROM data";
$result = $conn->query($sql) or die("cannot write");
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
echo "<pre>";
print json_encode(array('serverres'=>$rows));
echo "</pre>";
?>
Reference : How to Convert MySQL database table into JSON using PHP
Upvotes: 0