How to iterate over multiple result sets of a custom query? - php

I have a stored procedure in my mysql database which returns multiple query result sets.
I want to access these results in my cakephp(V3.4) project using following code statements.
$db = ConnectionManager::get('default');
$stmt = $db->execute("call mydatasp($paramlist)");
$result = array();
try{
do
{
$rowset = $stmt->fetchAll('assoc');
$result[]=$rowset;
} while($stmt->nextRowset());
}
catch(Exception $e){}
After execution of this code block, I m getting error as
[Cake\Error\FatalErrorException] Call to undefined method Cake\Database\Log\LoggingStatement::nextRowset()
How can I access these multiple query resultsets?

Related

PHP fetchAll() returning empty array

I have a prepared query with 3 result sets. I used fetch() for the first two since they only have one row each and they are appearing correctly in the View. For the 3rd result set, it consists of several transaction rows and I used fetchAll(), but it is empty, nothing appears in the view.
I tried modifying the proc to only return this transaction list, so in my code, I only called fetchAll(), but it is still empty. I've also tried running the EXEC statement in MS SQL Management Studio, and I can confirm that the 3rd query was supposed to return rows. I also didn't use fetchColumn() anywhere in the code. rowCount() returns 0.
I am now stuck. Please help.
Code snippet below:
try {
$conn = new PDO($dsn,$un,$pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
print("Error connecting to SQL Server.");
die(print_r($e));
}
$stmt = $conn->prepare("EXEC SomeStoredProc ?,?,?");
$stmt->execute([$id,$fromDate,$toDate]);
$firstResult_ = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->nextRowset();
$secondResult = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->nextRowset();
$transactions = $stmt->fetchall(PDO::FETCH_ASSOC);
$sample = $stmt->rowCount(); //returns 0

Unable to get more than one row returned using PDO

I am trying to perform a simple query to a MS SQL server database using (client) PHP PDO inside a loop and I am not able to retrieve more than one record.
The outer loop has a couple hundred thousand iterations (not using PDO) and the inner PDO fetch loop should return 2-4 records for each outer iteration.
This is what I have, not sure what I am doing wrong:
$dbh = '';
try {
$dbh = new PDO("sqlsrv:Server=mysqlserver, 1433;Database=mydatabase", '', '');
}
catch(Exception $e) {
echo "Error connecting to MS SQL database.";
error_log($e);
exit;
}
$foreign_keys = array(1563,89563,98272634); // etc.. The actual keys used here are obtained with other code not related to the problem.
foreach($foreign_keys as $foreign_key){
$sth = $dbh->prepare("select col1 from one_to_many_table where foreign_key=?");
$sth->bindParam(1, $foreign_key );
$sth->execute();
// expecting 2+ rows here ..
while($result = $sth->fetch( PDO::FETCH_ASSOC )){
echo $foreign_key.', '.$result['col1']."\n";
}
}
// Output:
// 1563, {value for col1} // first outer iteration, first PDO record returned
// --END -- Nothing else
I get just the first record returned from the PDO fetch from the first iteration of the outer loop.
I don't get any errors displayed on the screen or in the error log.
I am running this script from the CMD line on a Windows 7 machine with PHP 5.6.26 (cli).

Error getting data using PDO and PHP

I'm developing a web based software that uses MySQL and PHP on the backend.
I'm trying to obtain data with a complex query and in the end I just obtain the query.
function consulttimes(){
$pdo = connect();
try{
$consult = $pdo->prepare("SELECT credentials.realname, timestamp_greenhouse.* FROM times.credentials, times.timestamp_greenhouse WHERE timestamp_greenhouse.id = credentials.id;");
$consult->execute();
$consult->fetch(PDO::FETCH_ASSOC);
echo json_encode($consult);
//file_put_contents('times.json', $json);
}
catch(PDOException $e) {
echo $e -> getMessage();
}
}
I have all the databases and the query works perfectly on phpmyadmin.
Can someone help me with this?
Cheers!
I'm trying to obtain data with a complex query and in the end I just obtain the query.
The problem is because of this line,
echo json_encode($consult);
$consult is a PDOStatement object returned from the prepared statement. I believe you're trying to encode the row obtained from ->fetch(PDO::FETCH_ASSOC) method.
So first fetch the row from the result set, store it in a variable and then apply json_encode on it, like this:
// your code
$consult->execute();
$result = $consult->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);

php pdo returning only one result set

I'm new to php. I am making a call to store procedure that returns multiple result sets in MYSQL.
I can't seem to get PHP PDO to get the second result set. I only get the first. Any help is appreaciated
--more info
store procedure just makes to select statements like so
select * from Product where productId = id;
select url from Images where product_id = id;
PHP Code:
$conn = new PDO('mysql:host=localhost;dbname=salamancju_HardGraft', $this->userName, $this->password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$stmt = $conn -> prepare('call GetProductById(:id)');
$stmt->execute( array(':id' => $id));
$results = array();
do {
$results = $results + $stmt->fetchAll(PDO::FETCH_NUM);
} while ($stmt->nextRowset());
echo json_encode($results);
Your problem has nothing to do with stored procedures.
+ operator on arrays works not the way you think. Use [] instead:
do {
$results[] = $stmt->fetchAll(PDO::FETCH_NUM);
} while ($stmt->nextRowset());
will produce a nested array. If you want another format, please provide an example.
Save for this issue, your code is perfect. Most people who aren't new to PHP, won't be able to make it ever.

Randomly access to rowset/resultset with PDO Mysql and PHP

I want to access randomly to a result sets retuned from a Stored Procedure using PDO Mysql and PHP. I found PDOStatement::nextRowset but the access to the result sets seems to be sequential.
EDIT
I'm looking for some like this:
$pdo = new PDO("mysql:host=$server;port=$port;dbname=$dbname;charset=utf8", $user, $pass, array(PDO::ATTR_PERSISTENT => false));
$statement = "CALL FooSP()";
$query = $pdo->prepare($statement);
$query->execute();
$query->resultSet[1][0]["ColumnFoo"] // Second Resultset, first row, column "ColumnFoo"
$query->resultSet[3][1]["ColumnBar"] // third Resultset, second row, columna "ColumnBar"
$query->resultSet[0][0]["Column1"] // first Resultset, first row, columna "Column1"
Can anyone help me?
If You need all resultsets - just prefetch them using next rowset like this:
<?php
$sql = 'CALL multiple_rowsets()';
$stmt = $conn->query($sql);
$fetched_rowsets = array();
do {
$rowset = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rowset)
{
$fetched_rowsets[] = $rowset;
}
# This is important part.
} while ($stmt->nextRowset());
#Now You got the table with all data from all resultsets, fetched in PHP memory.
$fetched_rowsets[1][0]["ColumnFoo"];
$fetched_rowsets[3][1]["ColumnBar"];
$fetched_rowsets[0][0]["Column1"];
?>
Just remember that it can be memory consuming.

Categories