JSON output from MySQL works, but then white screen appears? - php

I've used the below code to generate JSON from a MySQL table. It works great when I'm only generating 2 arrays, but for some reason when I try and generate 3 or 4 arrays, I get the "white screen of death". I thought it was happening because I needed to bump up my PHP Memory Limit, but I've done that and still get the same problem. See below:
The code that works is:
<?php
//Create Database connection
$db = mysql_connect("localhost","user","dbpassword");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("dbname",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from customer", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['customerfname'] = $row['customerfname'];
$row_array['customerlname'] = $row['customerlname'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
But when I attempt to call more values, this is where I get the blank screen:
<?php
//Create Database connection
$db = mysql_connect("localhost","user","dbpassword");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("dbname",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from customer", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['customerfname'] = $row['customerfname'];
$row_array['customerlname'] = $row['customerlname'];
$row_array['customeremail'] = $row['customeremail'];
$row_array['customertel'] = $row['customertel'];
//push the values in the array
array_push($json_response,$row_array);
}
var_dump($json_response);
echo json_encode($json_response);
?>
Update**
The error appears to be with my last line (echo json_encode ($json_response);
The following output is generated when I add print_r($row) before that last line.
Array ( [id] => 1 [customerfname] => First [customerlname] => Last [customeremail] => test#test.com [customerphone] => 000-000-0000
Update 2
Adding var_dump($json_response); before the echo json_encode line results in the blank screen.

For future reference: If someone else is visiting this question due to having a similar problem, the error with the blank page occurred since the query returned too many rows and json_encode() did not seem to be able to handle it.
Try the following, and share with us your result,
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
//Create Database connection
$db = mysql_connect("localhost","user","dbpassword");
if (!$db)
die('Could not connect to db: ' . mysql_error());
mysql_select_db("dbname",$db);
mysql_query('SET CHARACTER SET utf8');
$result = mysql_query("select `customerfname`, `customerlname`, `customeremail`, `customertel` from customer", $db) or die("Error: ".mysql_error());
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$json_response[] = $row;
}
var_dump($json_response);
/* If the var_dump works, you can try and uncomment this section
if (function_exists('json_encode'))
{
echo json_encode($json_response);
echo "JSON Error: ".json_last_error();
}
else { echo "json_encode() is not supported"; }
*/
?>

When you use flcose($db) that is going to cause some trouble. remove that line.
flcose is used to close ressources such as writing to text files.
to close connection use mysql_close():
mysql_close($db);
and also Your loop can be reduce to this:
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
//push the values in the array
array_push($json_response,$row);
}
//Close the database connection
mysql_close($db);
echo json_encode($json_response);
and I would probably echo the json after closing the connection but thats no biggie.
And I find white screen of death very funny :D

Related

Error is Trying to get property 'id' of non-object, but seems object has

I am using PHP for 1st time.
I am just trying to fetch data from database. Here is my code -
try{
///try to connect with database
$conn=new PDO("mysql:host=localhost:3306;dbname=try", "root", "abcdef12");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex){
echo "error";
}
$mysqlcode="SELECT * FROM users";
$ret=$conn->query($mysqlcode);
foreach($ret as $ret1)
print $ret1->id;
in the browser,
showing this error:
Notice: Trying to get property 'id' of non-object in /opt/lampp/htdocs/secAsite/verifylogin.php on line 44
In the users table, I have 4 data.
In here, why $ret seems non object. I can't find anything wrong. How to fetch data. Or debug the object.
I have checked your code. Everything is fine. Just do this.
foreach($ret as $ret1)
print $ret1['id'];
You are not getting data because you are not fetching it..
you have to fetch the data before print it
updated code
$mysqlcode = "SELECT * FROM users";
$ret = $conn->query($mysqlcode);
if ($ret->num_rows > 0) {
// output data of each row
while($row = $ret->fetch_assoc()) {
echo "id: " . $ret["id"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
that'll work fine.
Before trying to use Object Oriented PHP, is much easier to understand Procedural. Take a look at the code below.
First, connect to database:
<?php
//Store log in info into variables
$servername = 'localhost';
$serveruser = 'youruser';
$serverpassword = 'yourpassword';
$serverdatabase = 'yourdatabase';
// Create connection
$conn = mysqli_connect( $servername, $serveruser, $serverpassword, $serverdatabase );
if ( !$conn ) {echo "Connection Fail" . mysqli_connect_error();}
//else {echo "Connected to database $serverdatabase";}
?>
Then, call the information from your database and your table and store it into an associative array $data
$sql = "SELECT * FROM `table`";
$result = mysqli_query($conn, $sql);
$data = mysqli_fetch_all($result, MYSQLI_ASOCC);
mysqli_free_result($result);
Now you can use the array to print the results with print_r
echo '<pre>'; print_r($data); echo '</pre>';}
Now you are ready to use foreach depending on your table columns,for example if you have ID column then
<?php foreach ($data as $value){
echo $value['id]."<br>";
} ?>
It will print out all the IDs. Hope this helps.

How to get data from MySQL with PHP

Hello all I am tryin to build IOS app and I need to get data my MySQL database. I do not know php. I found a tutorial https://codewithchris.com/iphone-app-connect-to-mysql-database/
In section 3 where we create PHP service I copy it and edit for mine information. PHP code is like that
<?php
//create connection
$con=mysqli_connect("localhost","myuserid","mypassword","i4142489_wp1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM treelibrary";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
I load it the my server and nothings pops up just the blank page... Is there any reason or where is my mistake. Thanks for helps.
Have a nice day.
I didn't read you're whole code, but I'm pretty sure you're trying to put the results into a JSON format and echo them.
Here's an easy way to do so;
<?php
//
// EDIT: dont use this code, scroll a little bit lower to see the edit I made.
//
//create connection
$con=mysqli_connect("localhost","myuserid","mypassword","i4142489_wp1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM treelibrary";
// Executes the SQL statement and puts results into $res
$res = $con->query($sql);
// Checks if there's any rows
if($res->num_rows > 0) {
// Puts all results in $row
$row = $res->fetch_assoc();
// echo & encode datas
echo json_encode($row);
} else {
echo "no data found";
}
// Close connections
mysqli_close($con);
Edit: The code above does work but only echoes the first row.
Here's one that actually echoes all of the rows in JSON format (tested).
<?php
//create connection
$con=mysqli_connect("localhost","myuserid","mypassword","i4142489_wp1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM treelibrary";
// Executes the SQL statement and puts results into $res
$res = $con->query($sql);
// Checks if there's any rows
if($res->num_rows > 0) {
// defines $data
$data = array();
// grabs all data and adds them to the $data array
while ($row = $res->fetch_assoc()) {
array_push($data, $row);
}
// echo & encode datas
echo json_encode($data);
} else {
echo "no data found";
}
// Close connections
mysqli_close($con);

json_encode and json_decode in mySql misunderstanding

I am stuck in my PHP page for a json_encode since a couple of days after having done 9999 tests.
The goal is to log on a swift app using mySql database.
So I guess i have something wrong in my query, and i dont know how to send answer of found/not found user in json_encode().
Here is my php code:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
// i get the email and password sent as parameter
// my swift code is working, and the next line is ok.
$logs[] = array('email' => $obj->email, 'pass' => $obj->pass);
//echo json_encode($logs); // to send back my logs (ok)
// Create connection
$con = mysqli_connect("localhost", "xx", "xx", "xx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//echo json_encode($logs);
// its working until here if i execute the previous line and put the rest in comment
// from the next line its making errors such :
// Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set."
$sql = "SELECT * FROM clients WHERE email = '".$logs['email']."'";
//echo json_encode($logs); //not working at this place if i put the rest in comment.
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object()) {
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
//check the corresponding password
if ( $logs['pass'] == $resultArray[4]) {
// i m not sure how to send the answer as a json
echo json_encode(true);
} else {
echo json_encode(false);
}
}
// Close connections
mysqli_close($con);
?>
If I try in php without all json stuff, its working since I put
$sql = "SELECT * FROM clients WHERE email = 'ben#test.be'";
as a test.
The following code works:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
$logs[] = array('email' => $obj->email, 'pass' => $obj->pass);
$con = mysqli_connect("localhost", "xx", "xx", "xx");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM clients";
if ($result = mysqli_query($con, $sql))
{
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
}
mysqli_close($con);
?>
But if I put $sql = "SELECT * FROM clients WHERE email = '$logs['email']'"; instead of $sql = "SELECT * FROM clients";
Its not working anymore. It doesn't like my conditional query. What did I misunderstood?

heading off in mysql?

PHP File:
<?php
require 'JSON.php'; // JSON.php
try
{
$connection = mysql_connect("localhost", "root", "autoset") or die("Could not connect: " . mysql_error());
mysql_query("SET NAMES utf8", $connection);
mysql_select_db(test, $connection);
$sql = "select * from Evaluation";
$sth = mysql_query($sql) or die("Query error: " . mysql_error());
// JSON
$json = new Services_JSON();
$rows = array();
while ($r = mysql_fetch_assoc($sth))
{
$rows[] = $r;
}
$output = $json->encode($rows);
echo $output;
mysql_close($connection);
}
catch (Exception $e)
{
echo $e->getMessage();
// Note: Log the error or something
}
?>
This is my JSON result:
[{"ENTERPRISE":"22","PERIOD":"53","EPS":"54","STOCKPRICE":"24","PER":"33"}]
How can I get fields without column names like this?
[22, 55, 54, 24, 33]
If you never want the MySQL data as an associative array keyed by column names, and always want a plain array with numeric indices, use mysql_fetch_array($sth,MYSQL_NUM) instead of mysql_fetch_assoc($sth) when extracting $row from the query resource. You should end up with an array of arrays in the resulting JSON, instead of an array of objects:
[[22, 55, 54, 24, 33]]
Decode it using json_decode, then from there, use array_values on the dictionary.
<?php
$values_data = array_values($data_from_sql);
$values_without_columns = json_encode($values_data );
?>

Getting JSON From An External MySQL Database Error?

i am using this tutorial and i dont know what is error is this
<?php
header('Content-type: application/json'); // this is the magic that sets responseJSON
// Connecting, selecting database
$link = mysql_connect($dbhost, $dbuser, $dbpass)
or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname) or die('Could not select database');
switch($_POST['op']) {
case 'getAllRecords': {
$table = $_POST['table'];
$query = sprintf("SELECT * FROM %s", mysql_real_escape_string($table));
// Performing SQL query
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$all_recs = array();
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$all_recs[] = $line;
}
break;
}
}
echo json_encode($all_recs);
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
error is :- null
Warning: mysql_free_result(): supplied argument is not a valid MySQL result resource in /home/ajay/public_html/mapleleafrealities.com/test.php on line 26
This is Example
My Error
if you have any simple example of getting json from external db please give me link or code
The op POST parameter is not "getAllRecords", so you're trying to encode something that doesn't exist, and free a result that was never taken. Try putting them inside.

Categories