json encoding not working in mysql fetch array - php

$return_arr = array();
$fetch = mysql_query("select `menu_item_name` from menu_option");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['menu_item_name'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);

Change this:
From
array_push($return_arr,$row_array);
To
$return_arr = array_push($return_arr,$row_array);

Run your SQL first and ensure that what you're getting back is in fact a result.
This can be done by either running
select menu_item_name from menu_option
manually in mysql shell or through something like MySQL Workbench.
Also, a print_r($return_arr) won't hurt to debug the issue you're having as the code itself should work fine. JSON_ENCODE works. The problem you're having is that you don't have an array.
Side note: It's better to use some form of ORM instead of writing low-level SQL for yourself. Have a look into Doctrine, Propel or Redbean, and save yourself some headaches.

Related

I'm trying to create JSON from a comma delimited array

I need to output like this.
{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.6192875","lng":"77.0261699"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6236227","lng":"77.0317984"},{"name":"","lat":"28.6244627","lng":"77.0322383"},{"name":"","lat":"28.6245415","lng":"77.0331425"},{"name":"","lat":"28.6245418","lng":"77.0331053"},{"name":"","lat":"28.6246156","lng":"77.0322415"},{"name":"","lat":"28.6242647","lng":"77.0316073"}
PHP Script
$sql="SELECT name,lat,lng FROM `in_point_creation` WHERE 1";
$result=mysql_query($sql);
while ($row=mysql_fetch_assoc($result)) {
$json_array = json_encode($row);
print_r($json_array);
}
Current Output
{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.6192875","lng":"77.0261699"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6236227","lng":"77.0317984"}{"name":"","lat":"28.6244627","lng":"77.0322383"}{"name":"","lat":"28.6245415","lng":"77.0331425"}{"name":"","lat":"28.6245418","lng":"77.0331053"}{"name":"","lat":"28.6246156","lng":"77.0322415"}{"name":"","lat":"28.6242647","lng":"77.0316073"}
Thanks
You need to create the entire object you need before calling JSON encode:
$sql="SELECT name,lat,lng FROM `in_point_creation` WHERE 1";
$result=mysql_query($sql); //You need to switch to mysqli , mysql is no longer a valid choice
$json_array = [];
while ($row=mysql_fetch_assoc($result)) {
$json_array[] = $row;
}
$jsonString = json_encode($json_array);
print_r($jsonString);
There are multiple ways to solve your "problem".
But first, don't use mysql_* functions => deprecated in PHP 5.5
Use mysqli_* functions instead.
If you have just a few hundred rows, you maybe could build an array with all items, like Paul Crovella and apokryfos said.
But if there are a multiple thousands of rows, you should prefer to write them out as quick as possible and don't save them to your RAM. Because PHP has limited space in RAM.
Maybe you could try it without loop:
$conn = mysqli_connect('host','username','password','database')
$query = 'SELECT name,lat,lng FROM `in_point_creation` WHERE 1';
$result = $conn->query($query);
$data = mysqli_fetch_all($result,MYSQLI_ASSOC);
echo json_encode($data);

echo json_encode after mysql_query failure

I'm currently trying to develop an Android app that communicates with a database. I use php scripts to communicate between my app and the database.
For error handling purposes, I was wondering if I could replace the die() function in php with something simliar to json_encode so that I can send an error code to my app.
mysql_query(/*the query*/) or /* something like echo json_encode*/
EDIT: here's an example of what I usually use,
$response['error1'] = "error in select query";
$result = mysql_query("SELECT id_product FROM `product`where id_category=$id_category") or die(mysql_error());
I tried something like:
$result = mysql_query("SELECT id_product FROM `product`where id_category=$id_category") or die(echo json_encode($response));
It doesn't work and I would like to know whether there is something else I can use.
Thanks for your help.
You can use an if on the result. If mysql_query() fails it returns false:
$result = mysql_query(/*the query*/);
if(!$result){
//Do stuff here, the query failed
//json_encode()
} else {
//Query succeeded
}
Sidenote: mysql_* is deprecated, I highly recommend to switch to mysqli_* or PDO
Try this code.it generate the JSON array loginsession
$return_arr = array();
//here start while loop for Mysql
$row_array['uid']=$uid;
$row_array['uname']=$uname;
$row_array['email']=$email;
$row_array['phone']=$phnumb;
$row_array['birthday']=$dob;
$row_array['address']=$address;
array_push($return_arr,$row_array);
// end your while loop
echo json_encode(array('loginsession' => $return_arr));

Blank result for some columns when php mysql_query, works in phpmyadmin

I've run into a problem that is making me go a bit crazy. I have imported some csv data into a table in my phpadmin database and am now using a php script with mysql_query() to run a simple select query on the database and convert the result into json format - e.g. SELECT clients FROM TABLE 29.
Basically, some of the columns in the table result in a json string after passing them through mysql_query() but others simply return a blank. I have fiddled for hours now and can't figure out why this is. The last bit of my code looks like this:
$myquery = "SELECT `clients` FROM `TABLE 29`";
$query = mysql_query($myquery) or die(mysql_error());
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
Any help would be greatly appreciated. Could it be something about the data in the table? I'm at a loss.
thank you!
UPDATE: the length of the strings in the column clients seems to be having an effect. When I replace all the text with something shorter (e.g. aaa instead of something like company name 111 - 045 - project name - currency - etc) it works. However, I need it to be able to handle long strings as I want it to just take whatever users happen to import into it... what am I doing wrong?
No, its not about the table, its about how you loop them. Example:
$data = array();
while($row = mysql_fetch_assoc($query)) { // While a row of data exists, put that row in $row as an associative array
$data[] = $row;
}
echo json_encode($data);
mysql_close($server);
exit;
Note: mysql is depreacted and no longer maintained. Use the improved version of the mysql extension which is mysqli or use PDO instead.
After checking all the rows of the data I discovered that the source of the problem was a 'é' - yes, an 'e' with an accent. Once I replaced it with a regular 'e' the problem went away. So much lost time for something so tiny :(

What are ways to run a MySQL query in PHP and output the result to an array in less space?

I'm getting really tired of writing:
$rows = array();
$result = $db->query("SELECT * FROM `table` WHERE `field`='".$information."'");
while($row = $result){
$rows[] = $row;
}
I tried a function, but it was kinda of messy feeling changing the input to field inputs. I thought maybe this or something similar would help:
$rows = array();
while($row = ($db->query("SELECT * FROM `table` WHERE `field`='".$information."'"))->fetch_assoc()){
$rows[] = $row;
}
but I get unexpected T_OBJECT_OPERATOR. I'm still on the line about using a function. Maybe there's a more efficient way of writing one. This is how I tried writing a function:
$array = SELECT ($db,$toSelect,$table,$where);
It still seems cumbersome, however. I would like something like $array = $db->("MYSQL");
The simplest solution is to write a function, which expects a database handle and a string query parameter, and returns all the rows.
$rows = fetch_all($db, "SELECT ...");
A bit more advanced is to write your own database class which wraps the database handle and adds such functionality.
$rows = $mydb->fetch_all("SELECT ...");
If you don't want to reinvent the wheel, simply use an existing ORM / PHP database library which does all this (and more) for you.
$db
->select('*')
->from('table')
->where('field', $information);
Note: http://www.php.net/manual/en/security.database.sql-injection.php - the third solution automatically solves this problem.

Passing PHP MySQL Result Object to Function

I'm trying to take a MySQL result row and pass it to a function for processing but the row isn't getting passed. I'm assuming this is because the actual row comes back as a object and objects can't get passed to function?
E.G
function ProcessResult($TestID,$Row){
global $ResultArray;
$ResultArray["Sub" . $TestID] = $Row["Foo"] - $Row["Bar"];
$ResultArray["Add" . $TestID] = $Row["Foo"] + $Row["Bar"];
}
$SQL = "SELECT TestID,Foo,Bar FROM TestResults WHERE TestDate !='0000-00-00 00:00:00'";
$Result= mysql_query($SQL$con);
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
$nRows = mysql_num_rows($Result);
for ($i=0;$i<$nRows;$i++)
{
$Row = mysql_fetch_assoc($Result);
$TestID = $Row[TestID];
ProcessResult($TestID,$Row);
}
}
What I need is $ResultArray populated with a load of data from the MySQL query. This isn't my actual application (I know there's no need to do this for what's shown) but the principle of passing the result to a function is the same.
Is this actually possible to do some how?
Dan
mysql_query($SQL$con); should be mysql_query($SQL,$con); The first is a syntax error. Not sure if this affects your program or if it was just a typo on here.
I would recommend putting quotes around your array keys. $row[TestID] should be $row["TestID"]
The rest looks like it should work, although there are some strange ideas going on here.
Also you can do this to make your code a little cleaner.
if(!$Result){
// SQL Failed
echo "Couldn't find how many tests to get";
}else{
while($Row = mysql_fetch_assoc($Result))
{
$TestID = $Row['TestID'];
ProcessResult($TestID,$Row);
}
}
mysql_fetch_assoc() returns an associative array - see more
If you need an object, try mysql_fetch_object() function - see more
Both array and object can be passed to a function. Thus, your code seems to be correct, except for one line. It should be:
$Result= mysql_query($SQL, $con);
or just:
$Result= mysql_query($SQL);

Categories