Object of class mysqli_stmt could not be converted to string on execute

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?

1 answer

  • answered 2018-05-16 06:35 Nick

    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;
    }