解析错误意外'*

I'm trying to make a script in PHP (using mariadb) that displays the amount of rows in a table and I'm trying to use the following script:

echo $conn->query('SELECT COUNT(*) FROM testtable')->fetchObject()->count(*);

But when I execute it, I get the following error:

Parse error: syntax error, unexpected '*'. How can I get around this? How can I resolve it

Have you tried like this? with fetchColumn()

$result = $conn->query("SELECT COUNT(*) FROM testtable");
echo $result->fetchColumn();

See example: http://php.net/manual/en/pdostatement.fetchcolumn.php#72609

Use fetchColumn when you only need to get one value.

echo $conn->query('SELECT COUNT(*) FROM testtable')->fetchColumn();

Your error is because count(*) would calling a method named count on the object with a first argument of *. Just an asterisk without quotes will result in a syntax error in PHP. You instead would need to use $obj->{'COUNT(*)'} to access a property with the name of COUNT(*), but it's much simpler to use fetchColumn.

The error is due to the last asterisk in the ->count(*) but even if this were fixed as Devon pointed out, it wouldn't work anyway since there is no count() method on what is returned by fetchObject().

Refer to the documentation for fetchObject here and fetchColumn here.

You could try

echo $conn->query('SELECT COUNT(*) FROM testtable')->fetchObject();

To get the whole row, but since the row has just one column, ->fetchColumn(0) is all you need.

The code

echo $conn->query('SELECT COUNT(*) AS rownum FROM testtable')->fetchObject()->rownum;

Worked for me