Fatal error cropped: PDOStatement class object cannot be converted to string

I get the following error when trying to match the values ​​in the database with the submitted in the form to check if the user exists.

Fatal error allowed: PDOStatement class object cannot be converted to a 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'; } } 
+6
source share
2 answers

mysql_query() and PDO are incompatible and cannot be used together. You are trying to pass a PDO statement object to mysql_query() , which expects a string. Instead, you want to get the rows from $stmt through one of the PDO fetch 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 } } 
+7
source

MySQL and PHP5 / PDO do not work with row return. After your new PDO () run the release:

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

Then it issues a request ...

 $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 will be either bool 0 or a null / throw error.

+1
source

Source: https://habr.com/ru/post/917241/


All Articles