2

Error:

PHP Catchable fatal error: Object of class mysqli_stmt could not be converted to string in common.php on line 33

I know there are many topic out there with this title, but I read all, and none of those similar to my code, on line 33:

if (!$sql->execute()) {
echo "Error: " . $sql . "<br>" . $sql->error; // --> this is line 33
}

This part belong to this codes:

class User {
    public function getId(){

    global $connection;
    $id = $_COOKIE['userid'];
    $userid = $_COOKIE['auth'];

    $sql = $connection->prepare("SELECT tel, hash FROM seller WHERE id = ?");
    $sql->bind_param("s", $id);
    if (!$sql->execute()) {
    echo "Error: " . $sql . "<br>" . $sql->error;
    }
    $sql->bind_result($tel, $hash);
    $sql->fetch();
    $sql->close();

    if(md5($hash) == $userid){
        $result = $tel;
    } else {
        $result = 0;
    }
    return $result;
    }
}

This morning I faced with this error suddenly and that code worked before. without no change I got this error. any idea?

The interesting part of this kind of error is, when I comment that line, I will get another similar error for another mysqli execute. why this happened?

I know what this error mean, but It just for until today, I didn't change anything and it just echo error of execute. so why?

Jack The Baker
  • 1,781
  • 1
  • 20
  • 51
  • 1
    `echo "Error: " . $sql...` <- right there, you are trying to concatenate `$sql` (which is a `mysqli_stmt` object) into a **string**. This cannot be done, so don't do it – Phil May 16 '18 at 06:11
  • 1
    You can get better error reporting from MySQLi and avoid checking the return values of its methods if you set `mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT)` before creating the DB connection. This will cause it to throw exceptions on errors – Phil May 16 '18 at 06:44

1 Answers1

0

As was pointed out in the comments, you are trying to express a mysqli_stmt object ($sql) as a string, which is not possible. You probably wanted to do this:

$query = "SELECT tel, hash FROM seller WHERE id = ?";
$sql = $connection->prepare($query);
$sql->bind_param("s", $id);
if (!$sql->execute()) {
    echo "Error: " . $query . "<br>" . $sql->error;
}
Nick
  • 138,499
  • 22
  • 57
  • 95
  • Error: `Error: Prepared statement needs to be re-prepared` – Jack The Baker May 25 '18 at 13:11
  • I'm not familiar with that error. Answers to this [question](https://stackoverflow.com/questions/4380813/how-to-get-rid-of-mysql-error-prepared-statement-needs-to-be-re-prepared) might help. – Nick May 26 '18 at 01:24