Count without using PDC rowCount

0

I'm new with PHP PDO , I'm using MVC and could not count the lines in the database using% / p>

Follow my code

model.php :

public function read($table, $fields, $where = null, $fetchMode = PDO::FETCH_ASSOC) {

    $where = isset($where) ? "WHERE {$where}" : "";

    $sql = $this->db->query("SELECT {$fields} FROM {$table} {$where} ");

    return $sql->fetchAll($fetchMode);

}

login_model.php

public function login() {
    $id = 1;
    $sql = $this->read('users', 'email', "id={$id}");
    print_r($sql);
    if (count($sql) >= 1) {
        echo 'é maior';
    } else {
        echo 'é menor';
    }
}

As you can see, I am using $obj->rowCount(); to do the count, because I could not do it using count() because of lack of logic: /

    
asked by anonymous 02.09.2015 / 00:03

3 answers

2

In your method returns only $sql and not results ( fetchAll() .

public function read($table, $fields, $where = null, $fetchMode = PDO::FETCH_ASSOC) {
    $where = isset($where) ? "WHERE {$where}" : "";
    $sql = $this->db->query("SELECT {$fields} FROM {$table} {$where} ");
    return $sql;
}

In the make call:

$sql = $this->read('users', 'email', "id={$id}");
echo $sql->rowCount();
    
02.09.2015 / 00:15
2
  

PDOStatement :: rowCount () returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

     

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behavior is not guaranteed for all databases and should not be relied on for portable applications. "

Source: link

EDIT:

If the last SQL query executed through PDOStatement was a select query, some databases may return the number of rows selected, however, other databases may not return, so the behavior is not guaranteed for all databases and therefore should not be invoked in portable applications.

It may not be perfect, but I find myself at work at the moment and this is the best I can do to help you.

    
02.09.2015 / 11:58
0

If you are using MySQL you can work around the situation by using sql_calc_found_rows and found_rows ().

Follow a link to an article that uses these features.

link

The most interesting is that it returns the total number of rows found even using the LIMIT and OFFSET classics. I use this feature a lot to make paging on the systems I do.

    
03.09.2015 / 04:54