从mysql数据库获取json数据的PHP代码

时间:2017-12-13 13:11:59

标签: php mysql json

我试图用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();
}
?>`

2 个答案:

答案 0 :(得分:2)

为什么不为此尝试json_encode()?为什么你尝试不必要的while循环。

$query = $conn->prepare('SELECT id, name, salary from afreen');

然后尝试使用json_encode()来获取Json格式的数据。

来源 - http://php.net/json_encode

答案 1 :(得分:0)

<?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();
}
?>