my question is how to translate get_result() to bind_result()
here is my index.php
//
$app->get('/tasks', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
// fetching all user tasks
$result = $db->getAllUserTasks($user_id);
$response["error"] = false;
$response["tasks"] = array();
// looping through result and preparing tasks array
while ($task = $result->fetch_assoc()) {
$tmp = array();
$tmp["id"] = $task["id"];
$tmp["task"] = $task["task"];
$tmp["status"] = $task["status"];
$tmp["createdAt"] = $task["created_at"];
array_push($response["tasks"], $tmp);
}
echoRespnse(200, $response);
});
//
here is the dbhandler.php
public function getAllUserTasks($user_id) {
$stmt = $this->conn->prepare("SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$tasks = $stmt->get_result();
$stmt->close();
return $tasks;
}
i am having all sorts of trouble trying to convert it to use bind_result() instead of get_result(), can some please give me some advice
thank you advance
Jason
here is my approach trying to convert it without luck please point out the problem thanks
index.php
///
$app->get('/companies', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
// fetching all user tasks
$result = $db->getAllUserCompanies($user_id);
$response["error"] = false;
$response["companies"] = array();
$companies = array();
while ($companies = $result->fetch()) {
$tmp = array();
$tmp["CompanyID"] = $companies["CompanyID"];
$tmp["UserID"] = $companies["UserID"];
$tmp["CompanyName"] = $companies["CompanyName"];
$tmp["CompanyAddress"] = $companies["CompanyAddress"];
$tmp["CompanyCity"] = $companies["CompanyCity"];
$tmp["CompanyIndustry"] = $companies["CompanyIndustry"];
$tmp["CompanyContact"] = $companies["CompanyContact"];
$tmp["CompanyNotes"] = $companies["CompanyNotes"];
$tmp["CreatedDate"] = $companies["CreatedDate"];
$tmp["UpdatedTime"] = $companies["UpdatedTime"];
$tmp["UpdatedBy"] = $companies["UpdatedBy"];
array_push($response["companies"], $tmp);
echoRespnse(200, $response);
}
});
dbhealper.php
//
public function getAllUserCompanies($user_id) {
$stmt = $this->conn->prepare("SELECT CompanyID, UserID, CompanyName, CompanyAddress, CompanyCity, CompanyIndustry, CompanyContact, CompanyNotes, CreatedDate, UpdatedTime, UpdatedBy FROM company WHERE UserID = ?");
$stmt->bind_param("i", $user_id);
//if ($stmt->execute()) {
($stmt->execute());
$companies = array();
$companies = $stmt->bind_result($CompanyID, $UserID, $CompanyName, $CompanyAddress, $CompanyCity, $CompanyIndustry, $CompanyContact, $CompanyNotes, $CreatedDate, $UpdatedTime, $UpdatedBy);
$stmt->close();
return $companies;
}
dbhealper.php //
You can try this
public function getAllUserCompanies($user_id) {
$stmt = $this->conn->prepare("SELECT CompanyID, UserID, CompanyName, CompanyAddress, CompanyCity, CompanyIndustry, CompanyContact, CompanyNotes, CreatedDate, UpdatedTime, UpdatedBy FROM company WHERE UserID = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
/* Store the result (to get properties) */
$stmt->store_result();
/* Get the number of rows */
$num_of_rows = $stmt->num_rows;
/* Bind the result to variables */
$companies = $stmt->bind_result($CompanyID, $UserID, $CompanyName, $CompanyAddress, $CompanyCity, $CompanyIndustry, $CompanyContact, $CompanyNotes, $CreatedDate, $UpdatedTime, $UpdatedBy);
return $companies;
/* free results */
$stmt->free_result();
}
if you look there is no much changes which has been done to it but to store the results I have added a line after $stmt->execute(); $stmt->store_result();
If your getting an error with $stmt->get_result, it may be because of this:
it works only with mysqlnd driver (http://us2.php.net/manual/en/m.... Solve it by using this:
DbHandler.php
/**
* Fetching all user tasks
* #param String $user_id id of the user
*/
public function getAllUserTasks($user_id) {
$stmt = $this->conn->prepare("SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($id, $task, $status, $created_at);
$tasks = array();
while($stmt->fetch()) {
$tmp = array();
$tmp["id"] = $id;
$tmp["task"] = $task;
$tmp["status"] = $status;
$tmp["createdAt"] = $created_at;
array_push($tasks, $tmp);
}
$stmt->close();
return $tasks;
}
and in index.php:
/**
* Fetching all user tasks
* #param String $user_id id of the user
*/
public function getAllUserTasks($user_id) {
$stmt = $this->conn->prepare("SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($id, $task, $status, $created_at);
$tasks = array();
while($stmt->fetch()) {
$tmp = array();
$tmp["id"] = $id;
$tmp["task"] = $task;
$tmp["status"] = $status;
$tmp["createdAt"] = $created_at;
array_push($tasks, $tmp);
}
$stmt->close();
return $tasks;
}
I am guessing the code sample is from http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-23/
I advise against using get_result() in any php code, simply because it requires mysqlnd to be installed, and is not supported in libmysql, which is the most common libary used for interfacing with mysql from php. instead, fetch() should be used to create an array of rows from the result set, or bind_result() for situations where you are only returning 1 row.
public function getAllUserTasks($user_id) {
$tasks = [];
$stmt = $this->conn->prepare("SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
if($stmt->num_rows > 0)
{
while($row = $stmt->fetch())
{
$tasks[] = $row;
}
$stmt->close();
}
return $tasks;
}
EDIT
to use it index.php
$app->get('/companies', 'authenticate', function() {
global $user_id;
$db = new DbHandler();
// fetching all user tasks
$response = $db->getAllUserCompanies($user_id);
if(!empty($response))
{
echoRespnse(200, $response);
}else{
//handle your error
}
});
Related
in symfony I want to get count from table in database but it return boolean !
$sql = "....";
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$res = $stmt->fetchAll();
foreach ($res as $key => $value) {
$resultatRequete = "SELECT count(id) from inscriptions where seance_id =
'".$value['seance_id']."' and is_confirmed is not null";
$stmt2 = $em->getConnection()->prepare($resultatRequete);
$result_req = $stmt2->execute();
$res[$key]["count_inscrit"] = $result_req ;
}
return $res;
The execute method return a boolean in order to success/failure, then you should fetch the result, as example:
// you can check on success ...
$success = $stmt2->execute();
$result_req = $stmt2->fetch();
$res[$key]["count_inscrit"] = $result_req ;
Hope this help
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.
First I was have:
public function getAllUserTasks($user_id) {
$stmt = $this->conn->prepare("SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result();
$tasks = $stmt->get_result();
$stmt->close();
return $tasks;
}
and this function have a problem with get_result() so instead get_result now I write function with BIND and FETCH:
public function getAllUserTasks($user_id) {
$stmt = $this->conn->prepare("SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$tasks = array();
$stmt->bind_result($id, $task, $status, $created_at);
$stmt->fetch();
$tasks["id"] = $id;
$tasks["task"] = $task;
$tasks["status"] = $status;
$tasks["created_at"] = $created_at;
$stmt->close();
return $tasks;
}
But on other file index.php now I get:<b>Fatal error</b>: Call to a member function fetch_assoc() on a non-object in <b>/home/agroagro/public_html/agroMobile/v1/index.php</b> on line <b>155</b><br />
so there is a code:
$app->get('/tasks', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
// fetching all user tasks
$result = $db->getAllUserTasks($user_id);
$response["error"] = false;
$response["tasks"] = array();
// looping through result and preparing tasks array
while ($task = $result->fetch_assoc()) { <--HERE IS LINE 155 and ERROR
$tmp = array();
$tmp["id"] = $task["id"];
$tmp["task"] = $task["task"];
$tmp["status"] = $task["status"];
$tmp["createdAt"] = $task["created_at"];
array_push($response["tasks"], $tmp);
}
echoRespnse(200, $response);
});
I try to solve this all day and dont work... Can somebody tell me what is exactly the problem here now?
What is the problem with this code?
Something like this (untested code):
public function getAllUserTasks($user_id) {
$stmt = $this->conn->prepare("SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?");
$stmt->execute(array($user_id));
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$app->get('/tasks', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
$response["error"] = false;
$response["tasks"] = $db->getAllUserTasks($user_id);
echoRespnse(200, $response);
});
I am in the process of working my RESTful Web Service with Slim Framework, and I got this error when I try to get data from 3 tables.
this is the function in my class:
public function getCard($card_id, $card_type_id, $user_id) {
$stmt = $this->conn->prepare("SELECT uc.id, c.card_name, ct.category, c.card_desc, c.card_picture ,c.status, c.created_at from cards c, user_cards uc, cards_type ct WHERE c.card_type_id = ct.card_type_id AND c.card_id = uc.card_id AND uc.user_id = ?");
if ($stmt == FALSE) {
die($this->conn->error);
} else {
$stmt->bind_param("iii", $card_id, $card_type_id, $user_id);
if ($stmt->execute()) {
$res = array();
$stmt->bind_result($id, $card_name, $category, $card_desc, $card_picture, $status, $created_at);
$stmt->fetch();
$res["id"] = $id;
$res["card_name"] = $card_name;
$res["category"] = $category;
$res["card_desc"] = $card_desc;
$res["card_picture"] = $card_picture;
$res["status"] = $status;
$res["created_at"] = $created_at;
$stmt->close();
return $res;
} else {
return NULL;
}
}
}
And this is the code in index.php:
$app->get('/cards/users/:card_id', 'authenticate', function($card_id, $card_type_id) {
global $user_id;
$response = array();
$db = new Card();
// fetch card
$result = $db->getCard($card_id, $card_type_id, $user_id);
if ($result != NULL) {
$response["error"] = false;
$response["id"] = $result["id"];
$response["card_name"] = $result["card_name"];
$response["category"] = $result["category"];
$response["card_desc"] = $result["card_desc"];
$response["card_picture"] = $result["card_picture"];
$response["status"] = $result["status"];
$response["createdAt"] = $result["created_at"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
Did i write something wrong ?
Check out this line:
$stmt = $this->conn->prepare("SELECT uc.id, c.card_name, ct.category, c.card_desc, c.card_picture ,c.status, c.created_at from cards c, user_cards uc, cards_type ct WHERE c.card_type_id = ct.card_type_id AND c.card_id = uc.card_id AND uc.user_id = ?");
The query might be hard to see, so I'll format just the query:
SELECT uc.id,
c.card_name,
ct.category,
c.card_desc,
c.card_picture,
c.status,
c.created_at
FROM cards c,
user_cards uc,
cards_type ct
WHERE c.card_type_id = ct.card_type_id
AND c.card_id = uc.card_id
AND uc.user_id = ?
Notice that it only has one question mark, indicating that you should only bind one parameter to your prepared statement.
So you should change this line:
$stmt->bind_param("i", $user_id); //have only one argument
I am trying to do following
$statement = $conn->prepare('SELECT * FROM myTable');
$statement->execute();
if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
{
return false;
}
$conn = null;
} catch(PDOException $e) {
throw $e;
return false;
}
return return json_encode(array('Result'=>$row);
Works and fetches all entries in a table make then JSON Array and send them,
However I want to make a query where selected ids must be send in a JSON Array
E.g 10, 20, 30
I assume that this will be done in a For loop perhaps
$statement = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
$row = $statement->fetch(PDO::FETCH_OBJ)))
Now suppose i have id's = 10,20,30 i want to append all of them in a JSON Array How can i do that?
just like return json_encode(array('Result'=>$row);
Edited Code
function GetMyMembers()
{
$myId = trim($_REQUEST['myId']);
try {
$conn = $this->GetDBConnection();
$statement = $conn->prepare('SELECT valId FROM memList WHERE myId=:myId' );
$statement->bindParam(':myId', $myId, PDO::PARAM_INT);
$statement->execute();
if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
{
return false;
}
// $row contains ALL THE ID'S
$placeholders = str_repeat('?,', count($row));
$placeholders = substr($placeholders, 0, -1);
$sql = "SELECT id, * FROM players WHERE id IN ($placeholders)";
$statement = $conn->prepare($sql);
$statement->execute($row);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
$conn = null;
} catch(PDOException $e) {
throw $e;
return false;
}
return $rows;
}
$statement = $conn->prepare('SELECT * FROM myTable');
$statement->execute();
$data = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC)))
{
$data[$row['id']] = $row;
}
return json_encode(array('Result'=>$data));
Btw, using raw API is not convenient. With Database abstraction library your code can be as short as 2 following lines:
$data = $db->getInd("id",'SELECT * FROM myTable');
return json_encode(array('Result'=>$data));
Edit:
if you have an array of ids, you need more complex code
$ids = array(1,2,3);
$data = array();
$statement = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
foreach ($ids as $id) {
$statement->bindValue(':id', $id, PDO::PARAM_STR);
$statement->execute();
$data[] = $statement->fetch(PDO::FETCH_OBJ);
}
return json_encode(array('Result'=>$data));
But while using Database abstraction library, there will be the same 2 lines:
$data = $db->getAll('SELECT * FROM myTable where id IN (?a)', $ids);
return json_encode(array('Result'=>$data));
Edit2:
if you need ids only
$statement = $conn->prepare('SELECT id FROM myTable');
$statement->execute();
$data = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC)))
{
$data[] = $row['id'];
}
return json_encode(array('Result'=>$data));
while using Database abstraction library, it's still 2 lines:
$ids = $db->getCol('SELECT id FROM myTable');
return json_encode(array('Result'=>$ids));
$ids = array(1,2,3);
$placeholders = str_repeat('?,', count($ids));
$placeholders = substr($placeholders, 0, -1);
$sql = "SELECT id, * FROM table WHERE id IN ($placeholders)";
$sth = $dbh->prepare($sql);
$sth->execute($ids);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
echo json_encode(array('Result' => $rows));
Based on additional comments:
Best option:
$sql = '
SELECT *
FROM table1 AS t1
INNER JOIN table2 t2
ON t2.foreign_key = t1.id
';
or
$sql = 'SELECT id FROM table1';
$sth = $dbh->prepare($sth);
$sth->execute();
$ids = $sth->fetchColumn();
//next look above