mysql以json格式查询和编码

时间:2013-12-20 10:01:55

标签: php mysql json

我正在使用这个简单的PHP代码以json格式编码MySql查询结果。 但不知道为什么它没有给我理想的输出。 我实际上是通过输入他们的'employee_number'来获取员工的详细信息。

<?php
require('DB_Connect.php');
require('config.php');
// check for post data
/*
 if (isset($_POST["employee_number"])) {
 $employee_name = $_POST['employee_number'];
 */
 //get a employee from employee_info table


$result = mysql_query("SELECT *FROM employee_info WHERE employee_number =9876543210");


if (!empty($result)) {
    // check for empty result
    if (mysql_num_rows($result) > 0) {

            $result = mysql_fetch_array($result);
    echo("Success !! Yoo");

    $employee = array();
            $employee["employee_number"] = $result["employee_number"];
    $employee["employee_name"] = $result["employee_name"];
    $employee["flag"]=$result["flag"];

        // success
        $response["success"] = 1;

        // user node
        $response["employee"] = array();

        array_push($response["employee"], $employee);

        // echoing JSON response
        echo json_encode($response);
    } else {
        // no employee found
        $response["success"] = 0;
        $response["message"] = "No employee found";

        // echo no users JSON
        echo json_encode($response);
    }
 }else {
    // no employee found
    $response["success"] = 0;
    $response["message"] = "No employee found";

    // echo no users JSON
    echo json_encode($response);
}
/*} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
*/
// echoing JSON response
echo json_encode($response);
?>

1 个答案:

答案 0 :(得分:1)

不推荐使用mysql_query。请改用mysqli或PDO。

确保正确格式化查询*注意空格 $result = mysql_query("SELECT * FROM employee_info WHERE employee_number = 9876543210");

您也可以回显$ result,因为您的员工阵列似乎没有做任何事情。

echo json_encode($result);