Help with fetching number of row from db with pdo

I have been trying to display number of rows from my db, but it displays 0 rows instead of 8 rows.

Here is my code:

$db_hostname=“127.0.0.1”;
$db_name="…";
$db_username="…";
$db_password=“dosso12345”;

 try {
            $pdo=new PDO("mysql:host=$db_hostname;db=$db_name", $db_username, $db_password);


                echo "Connection established";


        } catch (PDOException $e) {
            echo 'Cannot connect to database';
            exit;

        }

PHP code:

<?php include_once 'connection.inc.php'; try { $sql='SELECT count(*) FROM images'; $result = $pdo->prepare($sql); $result->execute(); $count= $result->rowCount(); echo $count; $result->closeCursor(); catch (PDOException $e) { echo "Error in code".$e->getMessage(); } ?>

[php]$count= $pdo->rowCount();[/php]

Wait, your doing a query. Just grab the results. Discount is when you are executing another query.

[member=72272]astonecipher[/member] Could you please show me with code what you have mentioned. I dont get properly

Thanks

It is a standard select statement, you need code to explain that?

I believe one could just do the following:

[php]$result = $pdo->query(“SELECT * FROM images WHERE id > 0”);
$count= $pdo->rowCount();[/php]

if one just wants to find out the total number of rows in a database table, for like astonecipher has stated it’s just simple select statement.

Selecting every column of every row is way overkill if all you want is a count and it is much, much slower. You may not notice it on a small DB but a large DB will.

Far better to do SELECT COUNT(*) FROM mytable

Sponsor our Newsletter | Privacy Policy | Terms of Service