how to fetch all the row of the result in php mysql? - php

In my table I have 2 records with companyid = 1 , but when I run the php below for companyid = 1 it returns only the first one !
How can I fetch all the records?
The php file:
if (isset($_GET["companyid"])) {
$companyid = $_GET['companyid'];
// get a product from products table
$result = mysql_query("SELECT * FROM `products`
WHERE companyid = $companyid;");
if (!empty($result)) {
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)){
$product = array();
$product["pid"] = $row["pid"];
$product["productname"] = $row["productname"];
}
$response["product"] = array();
array_push($response["product"], $product);
// success
$response["success"] = 1;
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no product JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
Using mysql_fetch_array is happening the same.
it returns {"product":[{"pid":"12371","productname":"test"}],"success":1}
when i run a query without parameters select * from table using mysql_fetch_array it returns all the rows ..

As NikiC pointed out you should not be using the mysql_ functions any longer, you can fetch the entire array in both PDO and mysqli, Here is a example to fetch all rows using the mysqli->fetch_all function, hope this helps!
//Database Connection
$sqlConn = new mysqli($hostname, $username, $password, $database);
//Build SQL String
$sqlString = "SELECT * FROM my_table";
//Execute the query and put data into a result
$result = $sqlConn->query($sqlString);
//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
//Copy result into a numeric array
$resultArray = $result->fetch_all(MYSQLI_NUM);
//Copy result into both a associative and numeric array
$resultArray = $result->fetch_all(MYSQLI_BOTH);

while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
php.net/mysql_fetch_assoc
I would recommend you to use PDO instead of mysql_
if (!empty($result)) {
Could be is_resource($result)

You need to loop through the result to pull all the rows:
while($row = mysql_fetch_assoc($result)){
//Do stuff
}
On a side note, you should be using at least mysqli or PDO instead of mysql_* functions.

I strongly believe the batch processing with Doctrine or any kind of iterations with MySQL (PDO or mysqli) are just an illusion.
#dimitri-k provided a nice explanation especially about unit of work. The problem is the miss leading: "$query->iterate()" which doesn't really iterate over the data source. It's just an \Traversable wrapper around already fully fetched data source.
An example demonstrating that even removing Doctrine abstraction layer completely from the picture, we will still run into memory issues:
echo 'Starting with memory usage: ' . memory_get_usage(true) / 1024 / 1024 . " MB \n";
$pdo = new \PDO("mysql:dbname=DBNAME;host=HOST", "USER", "PW");
$stmt = $pdo->prepare('SELECT * FROM my_big_table LIMIT 100000');
$stmt->execute();
while ($rawCampaign = $stmt->fetch()) {
// echo $rawCampaign['id'] . "\n";
}
echo 'Ending with memory usage: ' . memory_get_usage(true) / 1024 / 1024 . " MB \n";
Output:
Starting with memory usage: 6 MB
Ending with memory usage: 109.46875 MB
Here, the disappointing getIterator() method:
namespace Doctrine\DBAL\Driver\Mysqli\MysqliStatement
/**
* {#inheritdoc}
*/
public function getIterator()
{
$data = $this->fetchAll();
return new \ArrayIterator($data);
}
You can use my little library to actually stream heavy tables using PHP Doctrine or DQL or just pure SQL. However you find appropriate: https://github.com/EnchanterIO/remote-collection-stream

Related

Php Webservices: Get Multiple Records from MySQL and encode it in JSON array

I am newbie to PHP webservices using MySQL. I follow this tutorial. I created one table -> loan_applications using phpmyadmin. Currenlty I have 3 records in table related to id 1. I would like to retrive all 3 records and would like to encode it in json.
I tried multiple way and tried googling but unable to get proper json array in response. Here is my get_applications_list.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array();
if (isset($_GET['id'])) {
// receiving the post params
$id = $_GET['id'];
$applications = $db -> getApplicationsList($id);
if ($applications) {
// got applications successfully
$response["status"] = 0;
$response["id"] = $applications["id"];
$response["application_id"] = $applications["application_id"];
$response["requested_amount"] = $applications["requested_amount"];
$response["interest_per_day"] = $applications["interest_per_day"];
$response["gst"] = $applications["gst"];
$response["tenure"] = $applications["tenure"];
$response["processing_fees"] = $applications["processing_fees"];
$response["amount_user_get"] = $applications["amount_user_get"];
$response["amount_user_pay"] = $applications["amount_user_pay"];
$response["application_latitude"] = $applications["application_latitude"];
$response["application_longitude"] = $applications["application_longitude"];
$response["application_status"] = $applications["application_status"];
$response["created_at"] = $applications["created_at"];
$response["updated_at"] = $applications["updated_at"];
$response["message"] = "Applications details fetched successfully";
echo json_encode($response);
} else {
// applications failed to store
$response["status"] = 1;
$response["message"] = "Unknown error occurred in getting details!";
echo json_encode($response);
}
} else {
// receiving the post params
$response["status"] = 2;
$response["message"] = "Required parameters is missing!";
echo json_encode($response);
}
?>
Here is my DB_Functions.php
<?php
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
public function getApplicationsList($id){
$stmt = $this->conn->prepare("SELECT * FROM loan_applications WHERE id = ?");
$stmt->bind_param("s", $id);
$stmt->execute();
$applications = $stmt->get_result()->fetch_assoc();
$stmt->close();
if($applications){
return $applications;
}else {
return false;
}
}
}
?>
Here is response which I am getting :
{"status":0,"id":1,"application_id":1,"requested_amount":5000,"interest_per_day":"0.50","gst":18,"tenure":28,"processing_fees":"5.00","amount_user_get":4705,"amount_user_pay":5700,"application_latitude":"9.999999999","application_longitude":"9.999999999","application_status":1,"created_at":"2018-10-10 21:45:17","updated_at":"0000-00-00 00:00:00","message":"Applications details fetched successfully"}
I am getting only one record but i need all 3 record which associated with id 1. I tried lot but unable to get.
So multiple problems here
1 - Although unsure but Currenlty I have 3 records in table related to id 1 seems incorrect statement. If id is primary key, you cannot have 3 records against one id
2 - $stmt->get_result()->fetch_assoc(); will always return one row, to get multiple rows or collection of rows you will need to do it like following
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
3 - Its quite clear from following code that you are actually sending only one row back
if ($applications) {
// got applications successfully
$response["status"] = 0;
$response["id"] = $applications["id"];
$response["application_id"] = $applications["application_id"];
$response["requested_amount"] = $applications["requested_amount"];
$response["interest_per_day"] = $applications["interest_per_day"];
$response["gst"] = $applications["gst"];
$response["tenure"] = $applications["tenure"];
$response["processing_fees"] = $applications["processing_fees"];
$response["amount_user_get"] = $applications["amount_user_get"];
$response["amount_user_pay"] = $applications["amount_user_pay"];
$response["application_latitude"] = $applications["application_latitude"];
$response["application_longitude"] = $applications["application_longitude"];
$response["application_status"] = $applications["application_status"];
$response["created_at"] = $applications["created_at"];
$response["updated_at"] = $applications["updated_at"];
$response["message"] = "Applications details fetched successfully";
echo json_encode($response);
}
You should do it like this
$applications = getAllApplications(); //returns array of applications
$response['applications'] = $applications; // if they keys you want to send and database fields are same you don't need to set them separately
return json_encode($response);

My array didn't return anything in php

The array $response didn't return my item from database, it produce the result empty, causing my android application to display the error: "JSONException : End of input at character 0 of". Please provide any help, i will be appreciated.
<?php
include("connection1.php");
// connecting to db
$conn = mysqli_connect($hostname_localhost, $username_localhost, $password_localhost, $database_localhost);
/* check connection */
if (mysqli_connect_errno()) {
print "Error: Connect failed: %s\n";
exit();
}
mysqli_set_charset($conn, 'utf8');
$response = array();
/* Select queries return a resultset */
$query = "SELECT image FROM subject WHERE version = 'new'";
if ($result = mysqli_query($conn, $query)) {
$response = array();
while ($row = mysqli_fetch_array($result)) {
$item = array();
$item["image"] = $row["image"];
array_push($response, $item);
}
/* close result set */
mysqli_free_result($result);
}
echo json_encode($response);
/* close connection */
mysqli_close($conn);
?>
while ($row = mysqli_fetch_array($result)) {
array_push($response, base64_encode($row["image"]));
}
You set your $item as array and then you try to pass it as string. Basically $item = string and $item[] = array. So you just have to push the image value in the array you want. Try my code and give me some feedback. From what i see you made a circle out of it and got lost inside the while loop while you could just go simple.
As you will see here array push requires the array you want to store your values (array type) and the values (string type).

PHP mysqli_fetch_assoc not doing returning correct value

I have an old PHP code that has mysql in it.
It gets an array from a SELECT statement, adds it to a JSON object, as a property and echoes the encoded JSON.
I changed it around to use mysqli, but when I try to get the rows, and create an array out of them, it just returns nothing.
Here's the old mysql code:
$con = mysql_connect('host','account','password');
if (!$con)
{
//log my error
};
mysql_select_db("database_name", $con);
mysql_set_charset('utf8');
$sql = "SELECT field1 as Field1, field2 as Field2 from table where ID = '".$parameter."'";
$query = mysql_query($sql);
$results = array();
while($row = mysql_fetch_assoc( $query ) )
{
$results[] = $row;
}
return $results;
Version1: Here's the new one that I tried writing:
$con = mysqli_connect('host','account','password','database_name');
$sql = "SELECT field1 as Field1, field2 as Field2 from table where ID = '".$parameter."'";
$results = array();
if($result=mysqli_query($con, $sql))
{
while ($row=mysqli_fetch_assoc($result))
{
$results[] = $row;
}
return $results;
}
else
{
//error
}
Version2: Second thing I tried, which only returns 1 ROW:
...same as above until $sql
if($result=mysqli_query($con,$sql))
{
$row=mysqli_fetch_assoc($result);
return $row;
}
Version3: Or I tried to completely mirror the mysql structure like this:
$sql = "SELECT ...";
$query = mysqli_query($con, $sql);
$results = array();
while($row = mysqli_fetch_assoc( $query ) )
{
$results[] = $row;
}
return $results;
Wrapping the resulting array into the JSON:
$obj = new stdClass();
$obj->Data = $results;
$obj->ErrorMessage = '';
die(json_encode($obj)); //or echo json_encode($obj);
None of the mysqli version are working, so I was thinking there might be an important change in the way these arrays are created.
Any tips on what could be wrong on the first mysqli example?
With Version2 I can tell that the SQL connection is there, and I can at least select a row. But it's obviously only one row, than it returns it. It makes me think, that building up the array is the source of the problem, or it's regarding the JSON object...
LATER EDIT:
OK! Found a working solution.
ALSO, I played around with the data, selected a smaller chunk, and it suddenly worked. Lesson from this: the function is not responding the same way for 40 rows or for 5 rows. Does it have something to do with a php.ini setting? Or could there be illegal characters in the selection? Could it be that the length of a 'Note' column (from the db) is too long for the array to handle?
Here's the working chunk of code, that selects some rows from the database, puts them into an array, and then puts that array into an object that is encoded into JSON at the end, with a statusmessage next to it. Could be improved, but this is just for demo.
$con = mysqli_connect('host','username','password','database_name');
if (!$con)
{
$errorMessage = 'SQL connection error: '.$con->connect_error;
//log or do whatever.
};
$sql = "SELECT Field1 as FieldA, field2 as FieldB, ... from Table where ID='something'";
$results = array();
if($result = mysqli_query($con, $sql))
{
while($row = mysqli_fetch_assoc($result))
{
$results[] = $row;
}
}
else
{
//log if it failed for some reason
die();
}
$obj->Data = $results;
$obj->Error = '';
die(json_encode($obj));
Question is: how can I overcome the issue regarding the size of the array / illegal characters (if that's the case)?
Your "Version 1" seems to be correct from a PHP perspective, but you need to actually handle the errors - both when connecting and when performing the query. Doing so would have told you that you don't actually query a table, you're missing FROM tablename in the query.
Use mysqli_connect_error() when connecting, and mysqli_error($con) when querying to get back the actual errors. General PHP error-reporting might also help you.
The code below assumes that $parameter is defined prior to this code.
$con = mysqli_connect('host','account','password','database_name');
if (mysqli_connect_errno())
die("An error occurred while connecting: ".mysqli_connect_error());
$sql = "SELECT field1 as Field1, field2 as Field2
FROM table
WHERE ID = '".$parameter."'";
$results = array();
if ($result = mysqli_query($con, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
$results[] = $row;
}
return $results;
} else {
return mysqli_error($con);
}
Error-reporing
Adding
error_reporting(E_ALL);
ini_set("display_errors", 1);
at the top of your file, directly after <?php would enable you to get the PHP errors.
NOTE: Errors should never be displayed in a live environment, as it might be exploited by others. While developing, it's handy and eases troubleshooting - but it should never be displayed otherwise.
Security
You should also note that this code is vulnerable to SQL-injection, and that you should use parameterized queries with placeholders to protect yourself against that. Your code would look like this with using prepared statements:
$con = mysqli_connect('host','account','password','database_name');
if (mysqli_connect_errno())
die("An error occurred while connecting: ".mysqli_connect_error())
$results = array();
if ($stmt = mysqli_prepare("SELECT field1 as Field1, field2 as Field2
FROM table
WHERE ID = ?")) {
if (mysqli_stmt_bind_param($stmt, "s", $parameter)) {
/* "s" indicates that the first placeholder and $parameter is a string */
/* If it's an integer, use "i" instead */
if (mysqli_stmt_execute($stmt)) {
if (mysqli_stmt_bind_result($stmt, $field1, $field2) {
while (mysqli_stmt_fetch($stmt)) {
/* Use $field1 and $field2 here */
}
/* Done getting the data, you can now return */
return true;
} else {
error_log("bind_result failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("execute failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("bind_param failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("prepare failed: ".mysqli_stmt_error($stmt));
return false;
}
References
http://php.net/mysqli.prepare
How can I prevent SQL injection in PHP?

How to check if MySQL results returned empty in PHP?

How to check MySQL results are empty or not. If MySQL query results are empty then else condition should not be executed.
In case MySQL results in data there & in else condition my error my message is there but it is not showing any error message.
I have tried the following code but not showing any alert or echo message on the screen.
<?php
$sql = "select * from hall_search_data_1 where rent BETWEEN '".$_SESSION['amount1']."' AND '".$_SESSION['amount2']."'";
$res = mysql_query($sql);
if (!empty($res)) {
while ($row = mysql_fetch_row($res)) {
// here my data
}
} else {
echo "no results found";
}
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Check number of rows
$result = mysqli_query($conn, $sql);
$rowcount=mysqli_num_rows($result);
if($rowcount > 0){
echo "Number of rows = " . $rowcount;
}
else
{
echo "no record found";
}
You can use mysql_num_rows to get count of number of rows returned from query.
if(mysqli_num_rows($res) > 0)
{
// rest of your stuff
}
else
{
echo "No records found.";
}
Note: mysql is deprecated instead use mysqli or PDO as seen above
Security Tip First of all stop using the mysql_* functions because they are not secure for production and later versions has stopped support for this API. So if accidentally you used those function in production then you can be in trouble.
It is not recommended to use the old mysql extension for new development, as it was deprecated in PHP 5.5.0 and was removed in PHP 7. A detailed feature comparison matrix is provided below. More Read
For your answer you have to only check no of rows is zero or not
Read this Post at php documentation with Example.
mysqli_num_rows
mysql_* API has been removed from PHP long time ago. To access the database you should use PDO. Checking if PDO has returned any results is actually pretty simple. Just fetch the results and if the array is empty then there was nothing returned from MySQL.
$stmt = $pdo->prepare('SELECT * FROM hall_search_data_1 WHERE rent BETWEEN ? AND ?');
$stmt->execute([$_SESSION['amount1'], $_SESSION['amount2']]);
$records = $stmt->fetchAll();
if ($records) {
foreach ($records as $row) {
// your logic
}
} else {
echo 'No records found!';
}
There is also mysqli library and if you are stuck using it you have to do a little more work, but the idea is the same. Fetch all results and if nothing was fetched then it means MySQL returned no rows.
$stmt = $mysqli->prepare('SELECT * FROM hall_search_data_1 WHERE rent BETWEEN ? AND ?');
$stmt->bind_param('ss', $_SESSION['amount1'], $_SESSION['amount2']);
$stmt->execute();
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
if ($records) {
foreach ($records as $row) {
// your logic
}
} else {
echo 'No records found!';
}
You can use mysql_num_rows(); to check your query return rows or not
$sql = "select * from hall_search_data_1 where rent BETWEEN '".$_SESSION['amount1']."' AND '".$_SESSION['amount2']."'";
$res = mysql_query($sql);
$rows=mysql_num_rows($res);
if($rows>0)
{
echo "data return from query";
}else{
echo "data not return";
}
Note:- mysql is deprecated instead use mysqli or PDO

Store CI query into an array?

I've got the following function in a model, however it keep returning:
Message: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
And I for the life of me can't figure out why.
function getNames() {
$query1 = $this->db->query("SELECT * FROM Device_tbl ORDER BY Manufacturer");
$dev = array();
while($row = mysql_fetch_array($query1))
{
$manu = $row['Manufacturer'];
$mod = $row['Model'];
$dev[] = $manu.' '.$mod;
}
return $dev->result();
}
Can anyone help?
Answer for CodeIgniter is:
$query1 = $this->db->query("SELECT * FROM table");
foreach($query1->result_array() as $row)
{
$manu = $row['column1'];
$mod = $row['column2'];
echo $manu.' '.$mod;
}
return $query1->result();
The problem is you're mixing CodeIgniter database methods with built in PHP database methods. mysql_fetch_array expects a resource, not a CI query object.
Check out the docs on fetching results.
Sometimes, when you get a lot of data (lines) to process, you may want to use native php mysql functions like mysql_fetch_array to save memory (for best memory saving I prefer mysql_fetch_row). In this case you can use this :
try {
$query = $this->db->query("SOME QUERY");
while($row = mysql_fetch_row($query->result_id)) {
/* ... */
}
$query->free_result(); //we talked about memory saving right ;-)
} catch(Exception $e) {
/* ... */
}

Categories