I'm trying to convert an Array to JSON in PHP I have two identical pieces of code except for them referencing to different databases and data. could someone help me? The code that works:
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);
}
?>
The one that doesn't work:
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);
}
?>
I Asked my teacher too but he didn't know the answer either.