Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catchable fatal error: Object of class PDOStatement could not be converted to string

Tags:

php

mysql

pdo

I am getting the following error when attempting to match values on database with those passed in a form to check if a user exists.

Catchable fatal error: Object of class PDOStatement could not be converted to string

This is the code I'm using:

//Check users login details
    function match_login($username, $password){
            //If the button has been clicked get the variables
            try{

                $dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");

            } catch( PDOException $e ) {

                echo $e->getMessage();

            }
            $stmt = $dbh->prepare("SELECT * FROM mjbox WHERE username=? AND password=?");
            $stmt->bindParam(1, $username);
            $stmt->bindParam(2, $password);
            $stmt->execute();

            $result = mysql_query($stmt);
            if( mysql_num_rows($result) > 0 ){

                echo 'There is a match!';
            }else{
                echo 'nooooo';
            }
    }
like image 364
crmepham Avatar asked Jun 02 '12 12:06

crmepham


2 Answers

mysql_query() and PDO are not compatible and cannot be used together. You're attempting to pass the PDO statement object to mysql_query() which expects a string. Instead, you want to fetch rows from $stmt via one of PDO's fetching methods, or check the number of rows returned with rowCount():

$stmt = $dbh->prepare("SELECT * FROM mjbox WHERE username=? AND password=?");
$stmt->bindParam(1, $username);
$stmt->bindParam(2, $password);

if ($stmt->execute()) {

  // get the rowcount
  $numrows = $stmt->rowCount();
  if ($numrows > 0) {
    // match
    // Fetch rows
    $rowset = $stmt->fetchAll();
  }
  else {
    // no rows
  }
}
like image 135
Michael Berkowski Avatar answered Nov 18 '22 04:11

Michael Berkowski


MySQL and PHP5/PDO don't work well with returning the number of rows. After your new PDO(), issue:

$dbh->setAttribute(PDO::MYSQL_ATTR_FOUND_ROWS, true);   

Then issues your query...

$stmt = $dbh->prepare("SELECT * FROM mjbox WHERE username=? AND password=?");
$stmt->bindParam(1, $username);
$stmt->bindParam(2, $password);
$stmt->execute();

// number of rows returned
if($stmt->rowCount()){
    // ... matches
}else{
    // .. no match
}

Otherwise your rowCount would be either bool 0, or null/throw error.

like image 1
Mike Mackintosh Avatar answered Nov 18 '22 05:11

Mike Mackintosh