Echoing the value of count

$sql="SELECT count(*) FROM myTable";
$myTableCount=$dbc-> prepare ($sql);
$myTableCount=$myTableCount->fetch(); 

With the PDO database connection, the code above doesn’t produce any errors.

For getting the value of the SQL above, I added the code below.

echo $myTableCount['count'];

With the code above, it produces the Warning below.

I can’t find what is wrong.
How can I get the recordCount of myTable?

Try this which I have tested and it works:

      $sql   = "SELECT count(*) FROM myTable";
      $count = $qq->pdo->query($sql)->fetchColumn();
      print_r($count);

Nicked from:

https://phpdelusions.net/pdo_examples/count

Edit:

Please note that when creating the PDO Object a database name must be supplied

//=================================================
public function pdo() : object 
{
    $tmp = 'https://phpdelusions.net/articles/error_reporting';
    $INFO = <<< ____EOT
      <h3>
          Info from: &nbsp; 
          <a href="$tmp"> PhpDelusions.net  </a>
      </h3>
____EOT;

    $host = '127.0.0.1';
    $db   = 'myDatabsase';
    $user = 'joon1';
    $pass = 'password-goes-here;
    $port = "3306";
    $charset = 'utf8mb4';

    $options = [
        \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
        \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
        \PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    $dsn = "mysql:host=$host;dbname=$db;charset=$charset;port=$port";
    try
    {
      $this->pdo = new \PDO($dsn, $user, $pass, $options);
    } catch (\PDOException $e) {
        echo '<pre>'; print_r($e); 
      throw new \PDOException($e->getMessage(), (int)$e->getCode());
      die;
    }
  
    return (object) $this->pdo;
}//

Or you could use an as specifier

$sql   = "SELECT count(*) as tally FROM myTable";

which I think would work, but I haven’t tested. I picked tally just because count is almost certainly a reserved word and it saves me remembering how to show a backtick on the forum.

1 Like

It should work. I tend to use total because technically, you’re getting that total when you use count.

Since it’s only one column you’re selecting you may also want to look at fetchColumn

$statement = $dbc->prepare('SELECT count(*) FROM myTable');
$count = $statement->fetchColumn();

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.