Problem with num_rows

0

Good afternoon,

I have this code that is supposed to give me the number of books in the database, but it does not work.

public function getTotalBooks() {

            $sql = $this->db->prepare("SELECT * FROM libros");
            $result = $sql->execute();
            $rows = $result->num_rows();

            echo $rows;

        }

I get this error:

Fatal error: Uncaught Error: Call to a member function num_rows() on boolean in C:\xampp\htdocs\CBSLibrary\assets\private\classes\class.statics.php:17 Stack trace: #0 C:\xampp\htdocs\CBSLibrary\administration\settings\library.php(265): Statics->getTotalBooks() #1 {main} thrown in C:\xampp\htdocs\CBSLibrary\assets\private\classes\class.statics.php on line 17

I have tried to do it in a thousand ways after 1 hour searching the internet for the error, but I have not found one that works.

    
asked by Charlie Clewer 13.06.2017 в 20:05
source

1 answer

2

We have to:

  • PDO::prepare returns a PDOStatement , so the variable $sql is an object of this type.
  • PDOStatement::execute , returns bool , so the variable $result is a Boolean, it is saying is not an object, it is for this reason that you receive the error.

Solution:

One way to do it would be like this:

  • If the DB has the function COUNT()

    public function getTotalBooks() {
    
        $sql = $this->db->prepare("SELECT COUNT(*) FROM libros");
        $sql->execute();
        $rows = $sql->fetchColumn();
        echo $rows;
    }
    
  • If the DB does not have the function COUNT()

    public function getTotalBooks() {
    
        $sql = $this->db->prepare("SELECT * FROM libros");
        $sql->execute();
        $results = $sql->fetchAll(PDO::FETCH_ASSOC);
        echo count($results);
    }
    
answered by 13.06.2017 / 20:38
source