why my php app code shows only one result from database? [duplicate] - php

This question already has answers here:
mysqli query results to show all rows
(4 answers)
Sql array only showing first result
(4 answers)
Closed 5 years ago.
I have write these kind of codes multiple times and it always worked great but now that I am on a different system it shows only 1 result.
the query is simple
$HOST = 'localhost';
$USERNAME = 'root';
$PASSWORD = '';
$DATABASE = 'db_test';
$con = mysqli_connect($HOST,$USERNAME,$PASSWORD,$DATABASE);
$sql = "SELECT * FROM test ";
$res = mysqli_query($con,$sql);
$res_array = mysqli_fetch_assoc($res);
echo json_encode($res_array);
mysqli_free_result($res);
mysqli_close($con);
I wonder if there is any settings that I have to change before running the app

Seriously, it's all over the docs:
mysqli_fetch_assoc Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
Note "the fetched row" part.
You need to do put your gathering in a cycle
$rows = [];
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row
}
json_encode($rows);

This line $res_array = mysqli_fetch_assoc($res); will only fetch one record.
You need to loop over result-set object and get all data from that.So use while() loop like below
$res_array =[];
while($row = mysqli_fetch_assoc($res)){
$res_array[] = $row;
}
Reference:-
mysqli_fetch_assoc()

Replace this line
$res_array = mysqli_fetch_assoc($res);
with
while ($row = mysqli_fetch_assoc($res)) {
$res_array[] = $row;
}

Related

PHP Return Array in JSON , what happen this return include index? How To Fix? [duplicate]

This question already has answers here:
mysqli_fetch_array Gives Me Duplicate Rows
(4 answers)
Closed 3 years ago.
enter image description here
$table = $this->Execute("select * from data ");
$result = array();
while($row = mysqli_fetch_array($table))
{
array_push($result, $row);
}
return $result;
this my code,
i dont know why my result including the index
Its because of this statement:
while($row = mysqli_fetch_array($table))
You are getting numeric indexes as well as text keys.
Replace this by:
while($row = mysqli_fetch_assoc($table)) // will return only associate (string) keys.
OR
while($row = mysqli_fetch_array($table, MYSQLI_ASSOC)) // will return only associate (string) keys.
This will not include numeric indexes.
References:
mysqli_fetch_assoc()
mysqli_fetch_array()

json_encode doesn't display all array values [duplicate]

This question already has answers here:
php json_encode not working on arrays partially
(2 answers)
Closed 5 years ago.
I have a PHP script where it fetches all records from a table and encodes it to JSON. The table has a total of 246 records. echo count(); returns 246 as well.
The problem is, whenever I use json_encode, it doesn't display the values from the array at all, all I see is a blank page. But if I reduce the number of records to 13 instead of 246, it works and it displays the encoded JSON result. I have also tried to increase the memory_limit at my php.ini file to 4095M, but no avail.
$result = mysqli_query($con, "SELECT * FROM cities");
if (mysqli_num_rows($result) > 0) {
$response["cities"] = array();
$city = array();
while($row = mysqli_fetch_assoc($result)) {
$city[] = $row;
array_push($response["cities"], $city);
}
$response["success"] = 1;
echo json_encode($response);
}
Try below and you'll get to know what is happening exactly:
$json = json_encode($response);
if ($json)
echo $json;
else
echo json_last_error_msg();
json_last_error_msg() - Returns the error string of the last json_encode() or json_decode() call
Array "city" is expanding for each call and you are pushing the complete array on each iteration in loop .
Try :
while($row = mysqli_fetch_assoc($result)) {
array_push($response["cities"], $row);
}
It should work
Remove $response array push $row into $cities array. After pushing all city set the city and response in json_encode(); function like this echo json_encode(array("cities"=>$cities, "success"=>1));
if (mysqli_num_rows($result) > 0) {
$cities = array();
while($row = mysqli_fetch_assoc($result)) {
array_push($cities, $row);
}
echo json_encode(array("cities"=>$cities, "success"=>1));
}

Error while display json from sql database - PHP

I made a script to display data from online SQL database into JSON format.
The problem is, I don't have the format i was looking for, I get 2 [ more while i wanted only one:
A part of my script:
$sql = "select pseudo, dixsec from user;";
$result = mysqli_query($conn,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
$arrray = array("server_response" => array($rows));
print json_encode($arrray);
What i get (You can see here that i have 2 "["):
Json i get
How can i solve it and get only one "[" ?
$rows is already an array.
Try with: $arrray = array("server_response" => $rows);

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

Mysql fetch all rows and echo as json

I've got a database with 5 columns and multiple rows. I want to fetch the first 3 rows and echo them as an array. So far I can only get the first row (I'm new to PHP and mysql). Here's my PHP so far:
//==== FETCH DATA
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);
//==== ECHO AS JSON
echo json_encode($array);
Help would be much appreciated.
You need to loop through the results. mysql_fetch_row gets them one at a time.
http://php.net/manual/en/function.mysql-fetch-row.php
The code would end up like:
$jsonData = array();
while ($array = mysql_fetch_row($result)) {
$jsonData[] = $array;
}
echo json_encode($jsonData);
//json_encode()
PLEASE NOTE
The mysql extension is deprecated in PHP 5.5, as stated in the comments you should use mysqli or PDO. You would just substitute mysqli_fetch_row in the code above.
http://www.php.net/manual/en/mysqli-result.fetch-row.php
I do like this while quering an ODBC database connection with PHP 5.5.7, the results will be in JSON format:
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
Fetching results allowing edit on fields:
while( $row = odbc_fetch_array($result) ) {
$json['field_1'] = $row['field_1'];
$json['field_2'] = $row['field_2'];
$json['field_3'] = $row['field_1'] + $row['field_2'];
array_push($response, $json);
}
Or if i do not want to change anything i could simplify like this:
while ($array = odbc_fetch_array($result)) { $response[] = $array; }
What if i want to return the results in JSON format?, easy:
echo json_encode($response, true);
You can change odbc_fetch_array for mysqli_fetch_array to query a MySql db.
According to the PHP Documentation mysql_fetch_row (besides that it's deprecated and you should use mysqli or PDO)
Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.
so you need for example a while loop to fetch all rows:
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row;
}
echo json_encode($rows);
I leave it to you how to only fetch 3 rows :)
You need to put this in some kind of a loop, mysql_fetch_row returns results one at a time.
See example:
http://www.php.net/manual/en/mysqli-result.fetch-row.php#example-1794
$result = mysql_query( "SELECT * FROM $tableName ORDER BY id LIMIT 3");
$json = array();
while($array = mysql_fetch_row($result)){
$json[] = $array;
}
echo json_encode($json);

Categories