0

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

Mittal Patel
  • 2,732
  • 14
  • 23
coolcuber
  • 21
  • 3

4 Answers4

2

The code

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

Worked for me

coolcuber
  • 21
  • 3
  • That's true, using an alias will work, but since you're just getting a single value still, fetchColumn still makes more sense than using fetchObject. – Devon Bessemer Jul 06 '18 at 17:40
1

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.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
0

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

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

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.

geco17
  • 5,152
  • 3
  • 21
  • 38