Donny
Donny

Reputation: 699

Count does not work when I rewrote my code with PDO

I can't get my count to work once I changed from mysql to pdo. I am not sure what to do.

<tr>
    <td style="width: 125px">
        <a href="SystemsTechsPages/xgrh/xgrhCompleted1.php" target="_top">xgrh</a>
    </td>
    <td style="width: 125px" align="center">
        <a href="SystemsTechsPages/xgrh/xgrhCompleted1.php" target="_top">
        <?php 

        $stmt = $db->prepare("
            SELECT COUNT(*) FROM WHERE requests status='Completed' AND compDT=Curdate() AND compUser='xgrh'
        ");  
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
            echo $row['COUNT(*)'];  
        }  
        ?>
        </a>
    </td>
</tr>

Upvotes: 1

Views: 70

Answers (4)

CappY
CappY

Reputation: 1580

You should call $stmt->execute() before fetching. Prepared STMT is not sent to server, you should send it using execute.

Upvotes: 2

makhov
makhov

Reputation: 450

You should change your query:

SELECT COUNT(*) AS rows_cnt FROM table WHERE  status='Completed' AND compDT=Curdate() AND compUser='xgrh'

Then:

And use it like this:

$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{ 
   echo $row['rows_cnt'];  
}

Upvotes: 2

Kevin
Kevin

Reputation: 41875

First off, make sure to get the query right:

Its missing a table name

SELECT COUNT(*) FROM (what happened here? no table name)

WHERE status='Completed' 
AND compDT=Curdate() 
AND compUser = 'xgrh'

Secondly, you could just use an alias to better access the column name instead:

<?php 
// prepare
$stmt = $db->prepare("
    SELECT COUNT(*) AS total FROM table_name 
    WHERE status='Completed' 
    AND compDT = Curdate() 
    AND compUser = 'xgrh'
");
$stmt->execute(); // execute
$result = $stmt->fetch_assoc(PDO::FETCH_ASSOC);
$count = $result['total'];
echo $count;

?>

Upvotes: 3

Rasclatt
Rasclatt

Reputation: 12505

You can get the row count in PDO like so:

$count = $stmt->rowCount();

Upvotes: 0

Related Questions