0

i have a problem to use pdo for get COUNT(*).

    (...)

    public function getRowCount($sql, $bin = null)
    {
        $a = $this->conn->prepare($sql);
        if (!is_null($bin)) {
            foreach ($bin as $i => $val) {
                $a->bindParam(":$i", $val);
            }
        }
        $a->execute();
        return $a->fetchColumn();
    }

    (...)


If I use this, it works for me :

    // $obj = new class()
    echo $obj->getRowCount("SELECT COUNT(*) FROM `table_name` WHERE `a`=:a", [
        'a' => 'ABC'
    ]);

    // 1 or 2 and ...


But it doesn't work with two conditions :

    // $obj = new class()
    echo $obj->getRowCount("SELECT COUNT(*) FROM `table_name` WHERE `a`=:a AND `b`=:b", [
        'a' => 'ABC',
        'b' => 'DEF'
    ]);

    // only 0
ADyson
  • 57,178
  • 14
  • 51
  • 63
irmmr
  • 39
  • 1
  • 7
  • maybe you don't have any record with those values?.. – Alberto Sinigaglia May 17 '20 at 20:36
  • no it's not ..! – irmmr May 17 '20 at 20:45
  • 1
    dump the values you are injecting in the query and run the query manually – Alberto Sinigaglia May 17 '20 at 21:13
  • 1
    The most likely explanation is that the database doesn't contain any matching rows. Show us the table data you are using with this, and we can tell you what your query would expect to output. Or as Berto99 says, run your query manually in mysql directly and see what it produces. – ADyson May 17 '20 at 21:17
  • Thanks **@ADyson** and **@Berto99**. I need to use `BindParam` in the loop and I don't want to use this manually. There is no problem with manual use in pdo, so data and records are not a problem. – irmmr May 18 '20 at 09:21
  • 1
    Sorry I think I misunderstood the loop part. Anyway you don't need the loop, just pass the existing array to ->execute() directly - it's already in the correct format for that. Demo: http://sandbox.onlinephpfunctions.com/code/9fa99811e28f323ebfe598b63dd0bf7e8f256eb2 – ADyson May 18 '20 at 12:00
  • OK **@ADyson** . Thanks for your solution! – irmmr May 19 '20 at 17:13

0 Answers0