[英]Php code to get json data from mysql database
我试图用PHP中的SQL数据创建一个JSON对象。 怎么做? 这是我的方法,到目前为止还行不通。
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html; charset=utf-8');
$dns = "mysql:host=localhost;dbname=afreen";
$user = "root";
$pass = "";
try {
$conn = new PDO($dns, $user, $pass);
if (!$conn) {
echo "Not connected";
}
$query = $conn->prepare('SELECT id, name, salary from afreen');
$query->execute();
$registros = "[";
while ($result = $query->fetch()) {
if ($registros != "[") {
$registros .= ",";
}
$registros .= '{"id": "' . $result["id"] . '",';
$registros .= '"name": "' . $result["name"] . '"}';
$registros .= '"salary": "' . $result["salary"] . '"}';
$registros .= "]";
echo $registros;
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>`
为什么不尝试使用json_encode()呢? 为什么要尝试不必要的while循环。
$query = $conn->prepare('SELECT id, name, salary from afreen');
然后尝试json_encode()获得Json格式的数据。
来源-http: //php.net/json_encode
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
header('Content-Type: text/html; charset=utf-8');
$dns = "mysql:host=localhost;dbname=afreen";
$user = "root";
$pass = "";
try {
$conn = new PDO($dns, $user, $pass);
if (!$conn) {
echo "Not connected";
}
$query = $conn->prepare('SELECT id, name, salary from afreen');
$query->execute();
$registros= [];
while ($result = $query->fetch()) {
array_push($registros,array(
'id' =>$result["id"],
'title' =>$result["name"],
'salary' =>$result["salary"]
));
$output = json_encode(array("product"=>$registros));
print_r($output);
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.