Echoing the value of count

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

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();

Nicked from:


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

public function pdo() : object 
    $tmp = '';
    $INFO = <<< ____EOT
          Info from: &nbsp; 
          <a href="$tmp">  </a>

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

    $options = [
        \PDO::ATTR_EMULATE_PREPARES   => false,
    $dsn = "mysql:host=$host;dbname=$db;charset=$charset;port=$port";
      $this->pdo = new \PDO($dsn, $user, $pass, $options);
    } catch (\PDOException $e) {
        echo '<pre>'; print_r($e); 
      throw new \PDOException($e->getMessage(), (int)$e->getCode());
    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.