We help IT Professionals succeed at work.

Warning: PDOStatement::fetch() expects parameter 2 to be long, string

rgb192
rgb192 asked
on
4,888 Views
Last Modified: 2016-06-07
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
final example of fetch is generating this warning and no output
Warning: PDOStatement::fetch() expects parameter 2 to be long, string given in C:\wamp\www\oop-beg\pdo9.php on line 30

<?php
class secret_person{
  public $name;
  public $addr;
  public $city;
  public $other_data;
  
  function __construct($other=''){
    $this->addr=preg_replace('/[a-z]/','x',$this->addr);
    $this->other_data=$other;
  }
}

# connect to the database
try{
  $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);  
  $DBH->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
  #using the shortcut->query() method here since there is no variable
  #values in the select statement.
  $STH=$DBH->query('SELECT name,addr,city from test');
  #setting the fetch mode
  //$STH->setFetchMode(PDO::FETCH_CLASS | 'secret_person',array('stuff'));
  echo '<br>';
  $i=0;
  while($rowObj=$STH->fetch(PDO::FETCH_CLASS,'secret_person',array($i))){
    //echo $obj->name.'<br>';
    echo $obj->addr.'<br>';
    //echo $obj->city.'<br>';
  }
  
}
catch(PDOException $e){
  echo '<br>no results';
  echo '<br>$e:'.$e;
  echo '<br>$e->getMessage():'.$e->getMessage();
  file_put_contents('PDOErrors.txt',$e->getMessage(),FILE_APPEND);
}
$DBH=null;

Open in new window

Comment
Watch Question

Marco GasiFreelancer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Hi rgb192. See here: http://www.php.net/manual/en/pdostatement.fetch.php
The second parameter must be an integer value whgich indicates the cursor orientation. The parameter list you used here is valid for PDOStatement::setFetchMode (http://www.php.net/manual/en/pdostatement.setfetchmode.php)

So try to use

while($rowObj=$STH->fetch(PDO::FETCH_CLASS)){

letting default values to see if the result is what you expect it to be.
Marco GasiFreelancer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Oh, here you can find all predefined constants for PDO:

http://www.php.net/manual/en/pdo.constants.php
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Commented:
If you want to fetch your data into an object, then you set the FETCH_MODE and then call fetch(). You have commented out the FETCH_MODE line and tried to incorporate it into the fetch() call. You need something like this:

$STH->setFetchMode(PDO::FETCH_CLASS, 'secret_person');  
while($obj = $STH->fetch()) { 
   ...
}

Open in new window

Most Valuable Expert 2011
Author of the Year 2014

Commented:
IIRC that was a good article but it had an error in the code sample.

Some things that I found consistently useful when working with PDO:
// SET PDO TO TELL US ABOUT WARNINGS OR TO THROW EXCEPTIONS
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

Open in new window

Run a query and get a PDO Statement Object:
try
{
    $pdos = $pdo->query($sql);
}
catch(PDOException $exc)
{
    var_dump($exc);
    trigger_error($exc->getMessage(), E_USER_ERROR);
}
// SHOW THE RESULTS OF THE QUERY
var_dump($pdos);

// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
$num = $pdos->rowCount();

// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
echo "USING PDOStatement::FetchAll(PDO::FETCH_OBJ): ";
echo "<br/>" . PHP_EOL;
while ($row = $pdos->fetchAll(PDO::FETCH_OBJ))
{
    // ROW BY ROW PROCESSING IS DONE HERE
    foreach ($row as $key => $obj)
    {
        echo "$key: ";
        print_r($obj);
        echo PHP_EOL;
    }
}

Open in new window

Author

Commented:
Marqus and Chris suggested earlier lessons in the tutorial where I could successfully run the code.



Was I correct in making changes to Ray's code to make code run?

# connect to the database
try
{
  $pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); 
  // SET PDO TO TELL US ABOUT WARNINGS OR TO THROW EXCEPTIONS
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql='SELECT name,addr,city from test';
    $pdos = $pdo->query($sql);
}
catch(PDOException $exc)
{
    var_dump($exc);
    trigger_error($exc->getMessage(), E_USER_ERROR);
}
// SHOW THE RESULTS OF THE QUERY
var_dump($pdos);

// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
$num = $pdos->rowCount();

// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
echo "USING PDOStatement::FetchAll(PDO::FETCH_OBJ): ";
echo "<br/>" . PHP_EOL;
while ($row = $pdos->fetchAll(PDO::FETCH_OBJ))
{
    // ROW BY ROW PROCESSING IS DONE HERE
    foreach ($row as $key => $obj)
    {
        echo "$key: ";
        print_r($obj);
        echo PHP_EOL;
    }
}

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Commented:
You're not fetching your data into your own object, which is what I thought you wanted - you're just fetching the data into a blank object.
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Was I correct in making changes to Ray's code to make code run?
I would have isolated the try/catch blocks, but aside from that, I don't see anything grossly wrong with what you've got there.  But I don't have your data set to test it.  What do you get when you run it?
Marco GasiFreelancer
CERTIFIED EXPERT
Top Expert 2010

Commented:
I'm sorry, I recognize in that tutorial there is something I don't understand. the author suggests to use this code

while($rowObj=$STH->fetch(PDO::FETCH_CLASS,'secret_person',array($i))){

Open in new window


if one needs "to pass different data to the constructor for each object". rgb192 follows the tutorial strictly and he gets the error which is the reason of this thread.

I'm not able to explain why no one has never pointed at this if that code is wrong as it seems looking at Php.net manual.

@rgb192: only a side note: in your loop you should anyway increase $i value, otherwise the while loop doesn't make sense.
Hope Chris or Ray can clarify the problem: if the reason is that code is wrong, I apologize foe not having followed the tutorial as strictly as rgb192 does and for not having seen that error :(
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Commented:
@marqusG - Yes the code in the tutorial is wrong which is why I said he needed the setFetchMode() line (which he has commented) and then to use the fetch() method.

An alternative is to use the fetchAll() method which will take the arguments he's used:

while($rowObj=$STH->fetchAll(PDO::FETCH_CLASS,'secret_person',array($i))){

Open in new window

The $i doesn't necessarily need to be increased. As it stands the code will just pass the value of 0 to the class constructor, but the while loop is still needed to loop through the records.
Marco GasiFreelancer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Thanks for the explanation, Chris. Mmmmhh, how can i give you some points now? ;)
However, it seems rgb192 can simply replace $STH->fetch with $STH->fetchAll, isn't it?
This should solve the problem.
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Commented:
Yup - that would prevent his original error!
Although the while loop sets a variable called $rowObj but inside the loop he tried to access $obj, so there's another error waiting to happen :)

while($rowObj=$STH->fetch(PDO::FETCH_CLASS,'secret_person',array($i))){
    echo $obj->addr.'<br>';

Open in new window

Marco GasiFreelancer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Good eye!
Most Valuable Expert 2011
Author of the Year 2014

Commented:
I just looked back at the PDO article and was somewhat surprised at the number of comments indicating that it contained defective code.   I think upon seeing that, I might have turned away!

Author

Commented:
please tell me what line was the error and possible replacements because I am a pdo beginner.

For example
replace this line(s):
code here

with
this line(s):
code here








output of
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28311998.html#a39701428

0: stdClass Object ( [name] => cathy [addr] => 9 dark and twisty road [city] => cardiff ) 1: stdClass Object ( [name] => cathy [addr] => 9 dark and twisty road [city] => cardiff ) 2: stdClass Object ( [name] => cathy [addr] => 9 dark and twisty road [city] => cardiff ) 3: stdClass Object ( [name] => Cathy [addr] => 9 twisty and dark [city] => Cardiff )
Marco GasiFreelancer
CERTIFIED EXPERT
Top Expert 2010
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Most Valuable Expert 2011
Author of the Year 2014

Commented:
@ChrisStanyon: +1.

@rgb192: The examples in this article show how it's done.  I think I've recommended the article to you before, but if not, have a read of the PDO samples.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

Author

Commented:
I think this is marqus' code

<?php
//  print_r(PDO::getAvailableDrivers());
$host = 'hostedresource.com';
$user=$dbname = 'user';
$pass = 'Password';

class secret_person{
  public $name;
  public $addr;
  public $city;
  public $other_data;
  
  function __construct($other=''){
    $this->addr=preg_replace('/[a-z]/','x',$this->addr);
    $this->other_data=$other;
  }
}




# connect to the database
try
{
  $pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); 
  // SET PDO TO TELL US ABOUT WARNINGS OR TO THROW EXCEPTIONS
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql='SELECT name,addr,city from test';
    $pdos = $pdo->query($sql);
}
catch(PDOException $exc)
{
    var_dump($exc);
    trigger_error($exc->getMessage(), E_USER_ERROR);
}
// SHOW THE RESULTS OF THE QUERY
var_dump($pdos);

// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
$num = $pdos->rowCount();

// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
echo "USING PDOStatement::FetchAll(PDO::FETCH_OBJ): ";
echo "<br/>" . PHP_EOL;
while($rowObj=$STH->fetchAll(PDO::FETCH_CLASS,'secret_person',array($i))){
    echo $rowObj->addr.'<br>';
    // ROW BY ROW PROCESSING IS DONE HERE
    foreach ($row as $key => $obj)
    {
        echo "$key: ";
        print_r($obj);
        echo PHP_EOL;
    }
}

Open in new window


object(PDOStatement)#2 (1) { ["queryString"]=> string(31) "SELECT name,addr,city from test" } USING PDOStatement::FetchAll(PDO::FETCH_OBJ):

Fatal error: Call to a member function fetchAll() on a non-object in C:\wamp\www\oop-beg\pdo9a.php on line 46



what I think was Chris' code

<?php
//  print_r(PDO::getAvailableDrivers());
$host = 'hostedresource.com';
$user=$dbname = 'user';
$pass = 'Password';

class secret_person{
  public $name;
  public $addr;
  public $city;
  public $other_data;
  
  function __construct($other=''){
    $this->addr=preg_replace('/[a-z]/','x',$this->addr);
    $this->other_data=$other;
  }
}




# connect to the database
try
{
  $pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); 
  // SET PDO TO TELL US ABOUT WARNINGS OR TO THROW EXCEPTIONS
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql='SELECT name,addr,city from test';
    $pdos = $pdo->query($sql);
}
catch(PDOException $exc)
{
    var_dump($exc);
    trigger_error($exc->getMessage(), E_USER_ERROR);
}
// SHOW THE RESULTS OF THE QUERY
var_dump($pdos);

// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
$num = $pdos->rowCount();

// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
echo "USING PDOStatement::FetchAll(PDO::FETCH_OBJ): ";
echo "<br/>" . PHP_EOL;
$results = $STH->fetchAll(PDO::FETCH_CLASS, 'secret_person', array($i));
//$results is now an array of 'secret_person' objects
foreach ($results as $person):
   var_dump($person);
   echo $person->addr;
endforeach;

Open in new window



object(PDOStatement)#2 (1) { ["queryString"]=> string(31) "SELECT name,addr,city from test" } USING PDOStatement::FetchAll(PDO::FETCH_OBJ):

Fatal error: Call to a member function fetchAll() on a non-object in C:\wamp\www\oop-beg\pdo9b.php on line 46
Freelancer
CERTIFIED EXPERT
Top Expert 2010
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Most Valuable Expert 2011
Author of the Year 2014
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
I think the best answer is the Marqus telling me that I need $pdos not $sth in the examples because it showed me I maid the same mistake twice.

Thanks
i have same problem when i open inedx.php
i see this statment
Warning: PDOStatement::execute() expects parameter 1 to be array, string given in C:\xampp\htdocs\PHP_Course\eCommerce\1\admin\index.php on line 23
code in line 23
 $sth->execute($sql);
// This Code where the error
$sql = "SELECT `Username`,`Password` FROM `users` WHERE `Username` = '".$username." ' AND `Password` = '".$password." ' ";
        $sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
        $sth->execute($sql);
        $count = $sth->rowCount();
        echo $count;
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.