CREATE TABLE IF NOT EXISTS `tbl_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(25) NOT NULL,
`last_name` varchar(25) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `tbl_users`
--
INSERT INTO `tbl_users` (`id`, `first_name`, `last_name`) VALUES
(1, 'John', 'Doe'),
(2, 'Jane', 'Doe'),
(3, 'John', 'Cena'),
(4, 'Dwayne', 'Johnson');
បន្ទាប់មកយើងចាប់ផ្តើមសរសេរកូដ PHP ដើម្បីទាញយកទិន្នន័យពី table ដែលបានបង្កើតខាងលើ (ខាងក្រោមនេះជាកូដ PHP ប្រើប្រាស់ជាមួយ PDO dbconfig.php)
<?php
$DBhost = "localhost";
$DBuser = "root";
$DBpass = "";
$DBname = "dbjson";
try{
$DBcon = new PDO("mysql:host=$DBhost;dbname=$DBname",$DBuser,$DBpass);
$DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $ex){
die($ex->getMessage());
}
index.php
<?php
require_once 'dbconfig.php';
$query = "SELECT * FROM tbl_users";
$stmt = $DBcon->prepare($query);
$stmt->execute();
$userData = array();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$userData['AllUsers'][] = $row;
}
echo json_encode($userData);
?>
លទ្ធផល៖
{
"AllUsers": [
{
"id": "1",
"first_name": "John",
"last_name": "Doe"
},
{
"id": "2",
"first_name": "Jane",
"last_name": "Doe"
},
{
"id": "3",
"first_name": "John",
"last_name": "Cena"
},
{
"id": "4",
"first_name": "Dwayne",
"last_name": "Johnson"
}
]
}