I'm new to PHP and I don't understand why there is an extra word ARRAY infront of the JSON string.
Heres the output of JSON String:
Array{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1}
This is the PHP file:
<?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["UserID"] = $row["UserID"];
$user["FirstName"] = $row["FirstName"];
$user["Email"] = $row["Email"];
$user["Password"] = $row["Password"];
// push single User into final response array
array_push($response["Users"], $user);
}
// success
$response["success"] = 1;
echo $response;
// 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);
}
?>
Remove
echo $response;
which is printing the word Array. If you try to echo the array, it will display the word 'Array' rather than printing the content of an array itself. Use print_r() function to display the content of an array.
print_r($response);
With the exception of classes that use the __to_string magic method, echo and print will only output the string interpretation of a variable's value. Number types (integers and floats), strings, and (I think) booleans have a straightforward string representation. Any other variable (arrays, objects, resources) will either output nothing, their variable type, or throw a fatal error.
For arrays and objects, print_r() will go through each member/property and attempt to convert it to a string (print_r being shorthand for print_recursive). So print_r($response) will give you the full array.
Bear in mind that generally the full array is only useful to output for debugging. Passing a php string version of an array to javascript is likely to be useless.
Related
I am writing a script the will a echo a json object with values from the datatable when a request is sent to that script with a particular id, I have been able to get the records of member in an array but when I encode it into a json it become empty automatically but when I serialize the object and echo I will get all my record. I want the response in JSON.
<?php
include '../classes/RegisteredMemberDAO.php';
if (isset($_GET['getMember'])) {
$members = RegisteredMemberDAO::getAllRegistedMember();
//echo json_encode(RegisteredMemberDAO::getAllRegistedMember());
$sql = "SELECT * FROM members";
$mysqli = db_connect();
$result = $mysqli->query($sql);
$members = array();
while ($row = $result->fetch_assoc()) {
$member = new RegisteredMemberDAO();
$member->setEmail($row['email']);
$member->setSn($row['sn']);
$member->setUsername($row['username']);
$member->setPlan($row['plan']);
array_push($members, $member);
}
$mysqli->close();
//echo serialize($member);
echo json_encode($members);
}
Normally this error happens if the result contains mixed encoding characters.
To fix it, use JSON_UNESCAPED_UNICODE as second parameter to json_encode function.
echo json_encode($members, JSON_UNESCAPED_UNICODE);
To check error occurred during json_encode put this code after json_encode.
echo json_last_error_msg(); // Print out the error if any
die(); // halt the script
I am creating an Android Application that requires information to be retrieved from a MySQL database on a MAMP server. I have written PHP code to try retrieve the information from the database however there is no information being retrieved from the database. I have checked the code using PHP code checker and there is no issues found. Can anyone find any issues or provide any links to help. Thank you in advance.
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once('connect.php');
// connecting to db
//$db = new db_name();
// get all products from products table
$result = mysqli_query("SELECT * FROM tbl_book");
// check for empty result
if (mysqli_num_rows($result) > 0) {
// looping through all results
// book node
$response["books"] = array();
while ($row = mysqli_fetch_array($result)) {
// temp user array
$book = array();
$book["id"] = $row["id"];
$book["title"] = $row["title"];
$book["description"] = $row["description"];
$book["bookID"] = $row["bookID"];
// push single book into final response array
array_push($response["books"], $book);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No book found";
// echo no users JSON
echo json_encode($response);
}
?>
I want to send database records with a PHPH file via json to my app I am making with IntelXDK. Because I can't use PHP code with the Intel XDK, I needed to use JSON. I want to show the two records 'quote' and 'author' from my 'quotes' table on my screen. Someone helped me to this code but it just returns [null,null]instead of the two records I need.. I tried debugging but I am new to PHP so I can'get it to work.. Anyone who can help or sees an error in this code? Thanks!
PS: Yes I now there are already multiple questions asked on this subject by other people. I have read them all but none of them solves my question..
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
You have a bug in fetch_assoc() function call - remove $result parameter. If you had error reporting enabling, you should see:
Warning: mysqli_result::fetch_assoc() expects exactly 0 parameters, 1 given
Just change it to:
$row = $result->fetch_assoc();
In javascript to parse this response, just do this:
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("quote").innerHTML = obj[0];
document.getElementById("author").innerHTML = obj[1];
I think your problem is with fetch_assoc()
Try to use that :
$row = mysqli_fetch_assoc($result);
instead of
$row = $result->fetch_assoc($result);
It's works for me with your example
change this
$row = $result->fetch_assoc($result);
to
$row = $result->fetch_assoc();
Just change it to:
$row = $result->fetch_assoc();
Updated:
response = JSON.parse(xmlhttp.responseText);
you can now access them independently as:
reponse.quote and response.author
I am reading values from database and would like to store the values as a session object to be reused by the code. however, the code executes fine but does not store any values in the session storage.
JS code
$.getJSON("sessionstore.php", {"points": myjson}, function(data){
sessionStorage.user = data[0];
sessionStorage.usermail = data[2];
sessionStorage.supmail = data[4];
sessionStorage.repsupervisor = data[3];
sessionStorage.issupervisor = data[5];
});
php code
<?php
include 'mydbconn.php';
if (isset($_POST["points"])) {
$points = json_decode($_POST["points"]);
}
// decode the json data that is being passed
$usrname = $points->usrname;
$sql = "Select EmpName, EmpMail, RepSupervisor, SupMail, IsSupervisor from glusers where EmpName='$usrname'";
$result = $conn->query($sql);
$data = array();
while($row = $result->fetch_assoc()){
$data[] = $row;
};
echo $data[0];
die();
?>
There are no errors but the code does not execute.
Regards,
You are not outputting valid json. Note that $data[0] is a row of your result set - an array - so when you echo it in php you will output something like Array.
You need to change:
echo $data[0];
die();
to:
echo json_encode($data[0]);
die();
Edit: Also, you are fecthing associative arrays, so you would need to address them in your javascript as:
data.EmpName
data.EmpMail
// etc.
I'm trying to pull some records from the DB with the code below, but my echo json_encode($contacts); at the end of the code doesn't print anything. Nor does any echo put right above that.
<?php
require_once(dirname(__FILE__).'/ConnectionInfo.php');
//Set up our connection
$connectionInfo = new ConnectionInfo();
$connectionInfo->GetConnection();
if (!$connectionInfo->conn)
{
//Connection failed
echo 'No Connection';
}
else
{
//Create query to retrieve all contacts
$query = 'SELECT Numero_Leccion,Titulo_Leccion,Ejemplo_Leccion FROM leccion';
$stmt = sqlsrv_query($connectionInfo->conn, $query);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$contacts = array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$contact = array("Numero_Leccion"=>$row['Numero_Leccion'],"Titulo_Leccion"=>$row['Titulo_Leccion'],"Ejemplo_Leccion"=>$row['Ejemplo_Leccion']);
//Add the contact to the contacts array
array_push($contacts, $contact);
}
//Echo out the contacts array in JSON format
echo json_encode($contacts);
}
}
?>
Put error_reporting(E_ALL & ~E_NOTICE); ini_set('display_errors', '1'); somewhere on top of your script and see if there are any errors
(taken from Why echoing JSON encoded arrays won't produce any output)
Try this:
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$contacts[] = array("Numero_Leccion"=>$row['Numero_Leccion'],"Titulo_Leccion"=>$row['Titulo_Leccion'],"Ejemplo_Leccion"=>$row['Ejemplo_Leccion']);
}
header('Content-Type: application/json');
echo json_encode($contacts);