how fetch multiple rows from mysql using prepared statements - php

With prepare statement i am fetching only one row , i tried while to loop all rows but is only one row witch is being fetched.please assist me on how i fetch all rows from database instead of one
PHP function :
.....
public function StudentsOfParent($mobile){
$stmt = $this->conn->prepare("SELECT
a.id,
a.name,
a.mobile,
c.id as sutdentId,
c.user_id,
c.full_name,
c.school,
c.level,
c.year,
c.id
from users a
join students c
on a.id = c.user_id where a.mobile= ?");
$stmt->bind_param("i", $mobile);
if ($stmt->execute()) {
while ($user = $stmt->get_result()->fetch_assoc())
{
$stmt->close();
// return user's results
return $user;
}
}
else {
return NULL;
}
}
.....
External php file to access above function : retrieve.php:
<?php
include './DbHandler.php';
$db = new DbHandler();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['mobile'])){
$mobile = $_POST['mobile'];
$user = $db->StudentsOfParent($mobile);
if ($user != false) {
// user found successfully
$response["error"] = FALSE;
$response["user"]["id"] = $user["id"];
$response["user"]["sutdentId"] = $user["sutdentId"];
$response["user"]["user_id"] = $user["user_id"];
$response["user"]["full_name"] = $user["full_name"];
$response["user"]["school"] = $user["school"];
$response["user"]["level"] = $user["level"];
$response["user"]["year"] = $user["year"];
// $response["user"]["photo"] = $user["photo"];
echo json_encode($response);
// $json = json_encode($response);
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Sorry we could not find you !";
echo json_encode($response);
}
}
else {
// required post params is missing
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter is missing!";
echo json_encode($response);
}
?>

With prepare statement i am fetching only one row , i tried while to loop all rows but is only one row witch is being fetched.
That's because you're returning $user in the first iteration of while loop itself, the loop won't even go on for the 2nd iteration. Plus, you're also closing the statement object $stmt->close(); in the first iteration itself. Instead your code block should be like this:
// your code
$stmt->execute();
$result = $stmt->get_result();
$usersArr = array();
while ($user = $result->fetch_assoc()){
$usersArr[] = $user;
}
return $usersArr;
Now the returned $usersArr array is a multidimensional array, which you need to appropriately loop through to get all users' details. If you want to see the complete array structure, do var_dump($usersArr);.

Related

odbc_num_rows is not work

$stmt is execute and give Result in Print_r($stmt). Result is this "Resource id #4" but when Print_r($stmt) is put in if (odbc_num_rows($stmt) > 0) {Print_r($stmt);}. it's not give Result. and gone else conditon give message else condition.so How to Put odbc function instead of odbc_num_rows($stmt).if right Parameter pass query execute and gone if condition.
which Odbc function used in if condtion.
<?php
include 'Connection.php';
if(isset($_REQUEST["insert"]))
{
$user = $_GET['user'];
$pwd = $_GET['pass'];
$yid = $_GET['yid'];
$sql = "select RegNo, UserName, Pasword from Std_Reg where UserName= '$user' and Pasword = '$pwd' and YearID = $yid and IsActive = True";
$stmt = odbc_exec($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (odbc_num_rows($stmt) > 0)
{
print_r($stmt);
$stmt1 = odbc_fetch_array($stmt);
$product = array();
$product['RegNo'] = $stmt1['RegNo'];
$product['UserName'] = $stmt1['UserName'];
$product['Pasword'] = $stmt1['Pasword'];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
array_push($result["product"], $product);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["succes"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
odbc_close($conn); //Close the connnection first
}
}
?>
For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. The manual says-
Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.
one way around this behaviour is to do a COUNT(*) in SQL instead. See here for an example.

$stmt->fetch() is not fetching the data

I don't understand why my function is not getting the results and just getting null value. I'm using PhpStorm; all my connections are fine (Apache, MySQL, PhpMyAdmin) I've check them, also the other rest services are working.
This is my dbhandler.php file:
public function getRating($rating_id, $user_id) {
$stmt = $this->conn->prepare("SELECT ur.restaurant_id, ur.service_rating, ur.food_rating, ur.music_rating FROM user_ratings ur , user u WHERE u.user_id = ? AND u.user_id = ur.user_id AND ur.rating_id = ?");
$stmt->bind_param("ii", $rating_id, $user_id);
if ($stmt->execute()) {
$stmt->bind_result( $restaurant_id, $service_rating, $food_rating, $music_rating);
// TODO
//$rating_id = $stmt->get_result()->fetch_assoc();
$stmt->fetch();
$res = array();
$res["user_id"] = $user_id;
$res["rating_id"] = $rating_id;
$res["restaurant_id"] = $restaurant_id;
$res["service_rating"] = $service_rating;
$res["food_rating"] = $food_rating;
$res["music_rating"] = $music_rating;
$stmt->close();
return $res;
} else {
return NULL;
}
}
and this is my index.php file
$app->get('/userRatings/:rating_id', 'authenticate', function($rating_id) {
global $user_id;
$response = array();
$db = new DbHandler();
// fetch rating
$result = $db->getRating($rating_id, $user_id);
if ($result != NULL) {
$response["user_id"] = $result["user_id"];
$response["rating_id"] = $result["rating_id"];
$response["restaurant_id"] = $result["restaurant_id"];
$response["service_rating"] = $result["service_rating"];
$response["food_rating"] = $result["food_rating"];
$response["music_rating"] = $result["music_rating"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
The response of the request is:
{"user_id":19,
"rating_id":"171",
"restaurant_id":null,
"service_rating":null,
"food_rating":null,
"music_rating":null}
There is a problem in param values. Change param values as follows.
$stmt = $this->conn->prepare("SELECT ur.restaurant_id, ur.service_rating, ur.food_rating, ur.music_rating FROM user_ratings ur , user u WHERE u.user_id = ? AND u.user_id = ur.user_id AND ur.rating_id = ?");
$stmt->bind_param("ii", $user_id,$rating_id);
According to your sql first param should be $user_id. Not the $rating_id.
According to your parameter settings there is no record to fetch.

Run php action for every element

I have a php script which retrieves data from mysql db.
Everything works fine, but my problem is that this $result = $dao->joinedEvents($userId); returns an array of numbers and what I would like to do is to run this $secondResult = $dao->joinedEventsInfo($receivedIds); for every ID and this script I'm using right now returns data only for one ID.
This is part of my php script:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId); //This is getting the IDs array
if(!empty($result)) {
$receivedIds = $result["event_id"];
$ids = explode(",", $receivedIds);
foreach($ids as $id){
$secondResult = $dao->joinedEventsInfo($id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id" . $id;
}
}
} else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
And this is joinedEvents script:
public function joinedEvents($userId){
$returnValue = array();
$sql = "SELECT event_id from MyTable WHERE userId= '$userId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
This is joinedEventsInfo script:
public function joinedEventsInfo($eventId){
$returnValue = array();
$sql = "SELECT * FROM Events WHERE eventId = '$eventId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
Edit: Tha reason I need this is that I have two tables. In the first one I have just IDs and in the second one I have info. So first I need to get the IDs and then I need to get data for every ID I have just received.
Thank you very much , I'm totally stuck.
Based on the updated code snippets and the discussion below, it is found that $result is indeed an array, and the solution is:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId);
if(count($result)){
foreach($result as $array){
$event_id = $array['event_id'];
$secondResult = $dao->joinedEventsInfo($event_id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id: " . $event_id;
}
}
}else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
Have you tried array_map()?
That would allow you to call a php function on each member of an array easily.
Another way would be to use the common while ($row = mysql_fetch_array($result)) which would execute the code in the while loop for each row of your returned results. Note, you will likely have to change the mysql_fetch_array to something specific for your SQL connection.

Php+MySQL read results from a database and return an array of similar objects as JSON Array

User has items.
Each Item has lots of properties (price, date bought, condition, name)
I want to return a json array of all items and their properties
Here is my code:
$user_id = $_GET['user_id'];
$query_user_items = "SELECT product_id FROM user_products WHERE user_id = :user_id";
$item_ids_array = array();
$success = false;
try {
$sth = $connection->prepare($query_user_items);
$sth->execute(array(':user_id' => $user_id));
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$success = true;
} catch (PDOException $ex) {
$response["success"] = $http_response_server_error;
$response["message"] = $http_message_server_error . " " . $ex;
die(json_encode($response));
$connection = null;
}
if ($success) {
foreach($result as $key=>$value){
$query_get_item_details = "SELECT * FROM products WHERE product_id = :product_id";
$sth = $connection->prepare($qerty_get_item_details);
$sth->execute(array(':product_id'=> $value));
$record = $sth->fetch(PDO::FETCH_ASSOC);
$item_id = $record['product_id'];
$item_name = $record['product_name'];
$item_time_added = $record['product_time_added'];
$item_description = $record['product_description'];
$item_brand = $record['product_brand'];
$item_price_aquired = $record['product_price_aquired'];
$item_bought_from_place = $record['product_bought_from_place'];
}
/*
$response["success"] = $http_response_success;
$response["item_ids_array"] = $new_array;
echo json_encode($response);
Im not very good with php and I dont know what is going to happen at the second iteration (I dont know if Im iterating right as well)
I suppose $item_name will be overwritten with the second item's name, then the third and at the end I will only have only one object? How can I create an array of objects and their infos and then json_encode that?
Also, should I be declaring these variables outside of the foreach?
Your code could be shortened as follow (this way, you don't use any loop):
$query = "SELECT p.* FROM user_products u LEFT JOIN products p ON (p.product_id = u.product_id) WHERE u.user_id = :user_id";
try
{
$sth = $connection->prepare($query);
$sth->execute(array(':user_id' => $_GET['user_id']));
$response = $sth->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $ex)
{
$response["success"] = $http_response_server_error;
$response["message"] = $http_message_server_error . " " . $ex;
}
finally
{
$connection = null;
echo json_encode($response);
}
Then, in your ajax success handler, you can check if success or message is set (if that's the case, then an error occured). Otherwise, it is an array of results and you will loop through it
You don'y want to run a new query with every iteration.
You might want to use a single query to get all the data:
SELECT p.*
FROM user_products AS up
LEFT JOIN products AS p ON p.product_id = up.product_id
WHERE up.user_id = :user_id
In the PHP you can collect the data to array:
<?php
$data = array();
while($result = $sth->fetch(PDO::FETCH_ASSOC)){
$data[] = $result;
}
?><?=json_encode($data)?>

PHP doesnt display anything

Hi guys I'm new to PHP and I'm trying to display all info in my admin table. When I test my PHP file it gives me a blank page, here is my php code. There's no error but I get a blank page and nothing was returned when I execute it.
<?php
require('connect.inc.php');
require('admin.config.inc.php');
require('core.inc.php');
if (!empty($_POST)) {
//initial query
$query = "SELECT * FROM admin where username = :user";
$query_params = array(':user' => $_POST['username']);
//execute query
try {
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt -> fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["users"] = array();
foreach($rows as $row) {
$user = array();
$user["username"] = $row["username"];
$user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];
//update our repsonse JSON data
array_push($response["users"], $user);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}
} else {}
?>
Put this at the head of the script to see what response you get. Then others may be able to help you according to the error you get.
ini_set('display_errors',1);
error_reporting(E_ALL);
I see you have also began with:
if (!empty($_POST)) {
}
$_POST IS An associative array of variables passed to the current script via the HTTP POST method.
$_POST is defined where. this should be some thing like $_POST['user']
You begin with:
if (!empty($_POST)) {
which is empty by default, so you go directly to the else statement which is empty as well!
You are declaring $user = array(); inside the loop, It has to be outside of the loop
$user = array();
foreach($rows as $row) {
$user["username"] = $row["username"];
$user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];

Categories