php pdo returning only one result set - php

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.

Related

PHP SIMPLE DOM PDO select

I have in the database a list of links from which I want to take some data.
All the script is working, except the part when I'm taking the link from the DB and paste it in Simple DOM function.
"
include ('utile/db.php');
include_once('utile/simple_html_dom.php');
$dbh = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;", $username, $password);
$sth = $dbh->query("SELECT link FROM pilots where year = '2007' and Contry ='CZ' and zboruri <> '101' limit 3 ");
foreach ($sth as $url) {
functie ($url['link']);
}
function functie($lin){
$linkul=file_get_html("$lin");
// pages number
$paging = $linkul->find('div[class*=paging]',0);
echo $paging;
$numar=-4;
foreach($paging->find('a') as $element=>$item){$numar++;}
echo $numar;
}
"
I receive the following error:
Fatal error: Call to a member function find() on null in C:\xampp\htdocs\para\teste.php on line 269
If I change the link manually it will work.
I think it is something related how I extract the link from DB and insert it the function.
Thank you
The issue with fetchALL in foreach.
The line changed:
foreach($sth->fetchAll() as $url){
The final code that is working:
include ('utile/db.php');
include_once('utile/simple_html_dom.php');
$dbh = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;", $username, $password);
$sth = $dbh->query("SELECT link FROM pilots where zboruri > '101' limit 3");
foreach($sth->fetchAll() as $url){
functie ($url['link']);
}
function functie($lin){
var_dump($lin);
$linkul=file_get_html("$lin");
$paging = $linkul->find('div[class*=paging]',0);// pages number
echo $paging;
$numar=-4;
foreach($paging->find('a') as $element=>$item){$numar++;}
echo $numar;
}
Thank you for advices.
When I use PDO I use prepared statements, so the syntax on getting the result of the query is a little different... but I think that you need to fetch a row from your $sth since it would be a record set. Here's a snippit of what I do
$dbconn = new PDO('mysql:host='.$hostname.';port='.$dbPort.';dbname='.$dbName.';charset=utf8', $dbuser, $dbpass,array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result=$dbconn->prepare($query);
$result->execute($arr);
if(!$result){
// do your error handling, result is either false
// for error or contains a recordset
$errorMessage=$dbconn->errorInfo();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
while($row=$result->fetch()){
// do stuff here, $row is an associative array w/ the
//keys being the column titles in your db table
print_r($row);
}

php pdo prepared statment and transitions

I am trying to write a function that is supposed to receive any MySQL statement and apply it,
The basic idea is not to repeat needed code to write to Database, well what is needed to connect to Database is creating new PDO object, starting a transaction and preparing a statement, binding values to it, executing it,
so every time I want to access the Database I don't have to repeat these steps,
Here is a function that does that :
==============================================================================================
protected function applyQuery($statement, $bindparameters , &$values , $selectStatement, &$result){
try{
$dbh = DataBase::setConnection();// new PDO("MySQL= .....");
$dbh->beginTransaction();
$stmt = $dbh->prepare($statement);
if($bindparameters == true){
foreach($values as $key => $value){
$stmt->bindValue($key, $value);
}
}
$stmt->execute();
$dbh->commit();
if($selectStatement == TRUE){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}catch (PDOException $e){
$dbh->rollBack();
throw DataBase::$Errors[0];
}
}
============================================================================================
$statement = the desired statement (e.g 'SELECT * from users WHERE username = :username')///
$bindparameters = do we need to bind values (in this examples yes) so its value TRUE///
&$values = array by reference in this case equals = (':username' => 'User');///
$selectStatement = tells if using SELECT in statement ,in this case TRUE///
$result = array by reference in this case the final fetch result will be stored in it///
so in this example we get the following call to the function :
applyQuery('SELECT * from users WHERE username = :username', TRUE ,array(':username' => 'User') , TRUE , result )
My question is : will this code work ?
is the logical sequence of what it does and should do make sense ?
whats the difference between $stmt->execute and $dbh->commit ?
is omitting any line will cause failure to achieve the desired result
Please understand that I did lookup what is PDO and read a lot but unable to answer these questions!

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.

Getting a multi dimensional array from a mysql database

Right now im using Mysqli to retrieve data from a Mysql Database, The code im using is difficult to understand and from my understanding has depreciated functions or itself in entire is depreciated.
If i could get some insight and maybe some updated techniques on my Qoal of retrieving data from a mysql DB.
mysqli prepared statements
What i have so far is this:
$param = 1;
$mysqli = new mysqli("127.0.0.1", "user", "password", "databaseName");
$mysqli->query('SELECT reply_id FROM replies WHERE reply_topic = ? ORDER BY reply_date ASC');
$mysqli->bind_param('i',$param)
$mysqli->execute();
$row = bind_result_array($mysqli);
while($mysqli->fetch()){
$set[$row['']] = getCopy($row);
}
$mysqli->free_result();
return $set;
function bind_result_array($stmt)
{
$meta = $stmt->result_metadata();
$result = array();
while ($field = $meta->fetch_field())
{
$result[$field->name] = NULL;
$params[] = &$result[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params);
return $result;
}
function getCopy($row)
{
return array_map(create_function('$a', 'return $a;'), $row);
}
You need to clean up the call on the database first. $mysqli->query has send the query before you bound parameters and so on.
Replace with the following;
$stmt = $mysqli->prepare('SELECT reply_id FROM replies WHERE reply_topic = ? ORDER BY reply_date ASC');
$stmt->bind_param('i',$param)
$stmt->execute();
The $mysqli->prepare returns a new object that you should bind values to and then execute. It avoids SQL injection!
None of this is depreciated. mysqli_ is exactly what you should use.
As all you want is an array of the results, you can use the following code to do so - no user functions required.
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$set[] = $row['reply_id'];
}
For each row in the while, each field is saved into an array with the column name as the key. So $row['reply_id'] contains the value of the reply_id column in the database. Above I have saved this value to an array called $set, and when it loops over the next result row it saves the next value to that array too.
You can manipulate the result before or after saving it to the new array, as you see fit.
Hope this helps.

I can't get any result out from my mysql data base when I try to use PDO

I'm trying to use PDO for the first time but I can't get any result out. I've tryed several variants of script examples that I found but I don't get any result out. No errors either. This is my latest attempt.
$db = new PDO('mysql:host=localhost;dbname=mydb;charset=utf8', 'myuser', 'mypass');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = " SELECT * FROM pages WHERE seo=:seo ";
$stmt = $db->prepare($sql);
$values= array( 'seo' => $_REQUEST['p1'] );
$stmt->execute($values);
while($result = $stmt->fetch()){
echo $result['text'];
}
Is there a column named "text" in your table? Are you sure that the value you're supplying for the bind parameter exists in the seo column of the pages table?
For debugging, I suggest you try modifying the query a bit, to see if you are returning any rows:
SELECT * FROM pages WHERE 1=1 OR seo=:seo LIMIT 10
Also, echo out that value you are supplying for the bind parameter:
echo "bind parameter value = ", $_REQUEST['p1'];
You might also try dumping out the results after the fetch:
var_dump($result);
That should help narrow down the problem.

Categories