JSON parse Mysql query result in php pdo - php

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

Related

Request count sql in symfony return boolean not integer

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

How to fetch results in an array with ZF2

I am trying to get some distinct values from DB with ZF2 using Tablegateway.
$select = $this->sql->select($tableGateway->getTable());
$select->columns(array('city'));
$select->quantifier('DISTINCT');
$stm = $this->sql->prepareStatementForSqlObject($select);
$res = $stm->execute();
return $res;
This is returning an Iterate object, and I would like to have all the cities in an array. How can I do this ?
// whatever $select
$stm = $this->sql->prepareStatementForSqlObject($select);
$res = $stm->execute();
$resultSet = new \Zend\Db\ResultSet\ResultSet;
$resultSet->initialize($res);
foreach ($resultSet->toArray() as $row) {
// ...
}

MySQL data is not returned in PHP variables

<?php
require("config.inc.php");
$query = "Select 1 FROM dogs WHERE dog_id = :iddog ";
$query_params = array(':iddog'=> $_POST['iddogPHP2']);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$dono2 = $result ->fetchColumn(1);
$raca2 = $result ->fetchColumn(2);
$sex2 = $result ->fetchColumn(3);
$estado2 = $result ->fetchColumn(4);
$query = "Select * FROM dogs WHERE dispon = 'Sim' AND dono != '$dono2' AND estado = '$estado2' AND raca = '$raca2' AND sex != '$sexo2' ";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
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();
?>
This is my code and the problem is that the variables dono2, raca2, gender2 are not getting the values from the database. What's wrong in it?
Instead of SELECT 1 you need to use SELECT * in your first query.
$query = "Select * FROM dogs WHERE dog_id = :iddog ";
The following returns an array of results
$rows = $stmt->fetchAll();
So you would need to specify which one to reference.
$dono2 = $rows[0]['dono'];
$raca2 = $rows[0]['raca'];
$sexo2 = $rows[0]['sex'];
$estado2 = $rows[0]['estado'];
$rows = $stmt->fetchAll();
fetch all rows from database you need to specify which row you want if it's multiple row
$dono2 = $rows[0]['dono'];
$raca2 = $rows[0]['raca'];
$sexo2 = $rows[0]['sex'];
$estado2 = $rows[0]['estado'];
Try this code
$stmt = $db->prepare($query);
$stmt->bindParam(':iddog', $_POST['iddogPHP2']);
$stmt->execute($query_params);
$dono2 = $stmt ->fetchColumn(1);
$raca2 = $stmt ->fetchColumn(2);
$sex2 = $stmt ->fetchColumn(3);
$estado2 = $stmt ->fetchColumn(4);

slim php $stmt->get_result() to $stmt->bind_result()

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
}
});

PHP prepared statement not returning array

My array is empty when I'm binding an id variable. The table contains 5 columns that I'd like in an array. This is what I tried:
$records = array();
$id = 22;
if($results = $db->prepare("SELECT * FROM categories WHERE id = ?")) {
$results->bind_param('i', $id);
$results->execute();
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results->free();
}
}
print_r($records);
you are binding param 'i' but using a '?' placeholder. Use one of these:
if($results = $db->query("SELECT * FROM categories WHERE id = ?")) {
$results->bind_param(1, $id);
or
if($results = $db->query("SELECT * FROM categories WHERE id = :i")) {
$results->bind_param(':i', $id);
See http://www.php.net/manual/en/pdostatement.bindparam.php for more examples.

Categories