Reputation: 4740
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';
}
}
Upvotes: 6
Views: 13515
Reputation: 14237
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.
Upvotes: 1
Reputation: 270607
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
}
}
Upvotes: 7