简体   繁体   中英

PDO Union Count

public function totalRecords($keyword) {
    $sql = "SELECT COUNT(uid) FROM user_information WHERE title LIKE ? OR name LIKE ? OR surname LIKE ? 
          UNION ALL
          SELECT COUNT(id) FROM groups WHERE name LIKE ?";
    $query = $this->db->prepare($sql);
    $query->execute(array("%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%"));
    return $query->rowCount();
}

I am trying to create pager, and i need to total records of search term.

Above code does not work, it always return 0. How can i do this ?

rowCount()

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

So you have to use fetch() with sum()

public function totalRecords($keyword) {
    $sql = "SELECT SUM(num) as num  FROM
             (SELECT COUNT(uid) as num FROM user_information WHERE title LIKE ? OR name LIKE ? OR surname LIKE ? 
             UNION ALL
            SELECT COUNT(id)as num FROM groups WHERE name LIKE ?)
            AS X";
    $query = $this->db->prepare($sql);
    $query->execute(array("%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%"));
    $Total = $query->fetch();
   return $Total['num'];
}

From the documentation on rowCount :

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 behaviour is not guaranteed for all databases and should not be relied on for portable applications.

Since you are using a UNION ALL without ny GROUP BY s in sub-queries, the fetched results would be 2 rows. One showing the count from user_information table and another for the groups table. You probably want to use ->fetch() statement here.

Also, since all the placeholders in your query are for the same values, use a named placeholder:

public function totalRecords($keyword) {
    $sql = "SELECT COUNT(uid)
        FROM user_information
        WHERE title LIKE :kwd
            OR name LIKE :kwd
            OR surname LIKE :kwd 
        UNION ALL
        SELECT COUNT(id)
        FROM groups
        WHERE name LIKE :kwd";
    $query = $this->db->prepare($sql);
    $query->execute( array(":kwd" => "%$keyword%") );
    // the resulting array needs to be processed accordingly
    return $query->fetchAll();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM