相同的数组 - > JSON代码不起作用

时间:2016-02-10 16:24:43

标签: php json

我正在尝试在PHP中将数组转换为JSON我有两个相同的代码片段,除了它们引用不同的数据库和数据。有人能帮助我吗? 有效的代码:

    get_all_products.php
<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT * FROM products") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["products"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp product array
        $product = array();
        $product["pid"] = $row["pid"];
        $product["pname"] = $row["pname"];
        $product["pprice"] = $row["pprice"];
        $product["pamount"] = $row["pamount"];

        // push single product into final response array
        array_push($response["products"], $product);
    }
    // success
    $response["success"] = 1;

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

    // echo no users JSON
    echo json_encode($response);
}
?>

不起作用的那个:

    post2.php
<?php

/*
 * Following code will list all the users
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all users from users table
$result = mysql_query("SELECT * FROM users") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // users node
    $response["users"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $user = array();
        $user["ID"] = $row["ID"];
        $user["name"] = $row["name"];
        $user["balance"] = $row["balance"];
        $user["pin"] = $row["pin"];

        // push single user into final response array
        array_push($response["users"], $user);
    }
    // success
    $response["success"] = 1;

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

    // echo no users JSON
    echo json_encode($response);
}
?>

我也问我的老师,但他也不知道答案。

0 个答案:

没有答案