How to return the result of a select with Prepared statement?

Asked

Viewed 498 times

0

Guys, I’m not getting back the result of a search with Prepared statement.

Here’s the code:

public function search($obj) {
        $connection = new Connection();
        $this->db = $connection->conectar();

        /* String SQL de buscar todos os registros */
        $stringSQL = "SELECT * FROM fornecedor WHERE cnpj = :cnpj";

        $statement = $this->db->prepare($stringSQL);

        /* parâmetros do prepared statement */
        $statement->bindparam(":cnpj", $obj->getCnpj());

        /* executa a query */
        $statement->execute();

        $result = $statement->get_result();

        unset($this->db);
        return $result;
    }       

I’m making the following mistake:

Fatal error: Call to Undefined method Pdostatement::get_result() in C: xampp htdocs inove gentelella-master Production Classes Persistence Vendordorcrud.php on line 123

Some help?

Thank you

  • Is mixing PDO with a Mysqli function...

  • @Inkeliz thank you. It’s true.

1 answer

4


public function search($obj) {
    $connection = new Connection();
    $this->db = $connection->conectar();

    /* String SQL de buscar todos os registros */
    $stringSQL = "SELECT * FROM fornecedor WHERE cnpj = :cnpj";

    $statement = $this->db->prepare($stringSQL);

    /* parâmetros do prepared statement */
    $statement->bindparam(":cnpj", $obj->getCnpj());

    /* executa a query */
    $statement->execute();

    /* retorna o resultado */
    $statement->fetchAll(\PDO::FETCH_ASSOC);
    return $statement;
}       

$stmt->fetchAll( PDO::FETCH_ASSOC); // This row returns all results found in execute().. If you want to return a single result use $stmt->fetch( PDO::FETCH_ASSOC); I did not test anymore I believe it is working.. Good luck!

  • Thank you. The only change I had to make to your code to get the expected result was: $statement = $statement->fetchAll( PDO::FETCH_ASSOC); If I printed only $statement, I would get Pdostatement Object ( [queryString] => SELECT * FROM supplier WHERE cnpj = :cnpj ). Anyway, it worked. Thank you

  • Thank you very much. I’m so glad I could help you out!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.