-1

I just start using MySQL, and try to write a little article generator. For that I need to count articles entities in database. This expression works fine when I write it in mariaDB command-line:

$articles_amount = "SELECT COUNT(*) FROM post";
$articles_amount = @mysqli_query($dbc, $articles_amount);

SELECT COUNT(*) FROM post; output in mariaDB client:

+----------+
| COUNT(*) |
+----------+
|        3 |
+----------+

When I tried to print out the value of $artcles_amount I get an empty string. Database connection works well for other statements.

siery
  • 467
  • 3
  • 20
  • 1
    I'm weak with PHP, but you may try aliasing your `COUNT(*)`, e.g `COUNT(*) AS cnt`, then accessing that alias from your PHP script. – Tim Biegeleisen Feb 26 '18 at 06:40

1 Answers1

1

You just made the query. You need to do something more like:

$res = $dbc->query('SELECT COUNT(*) count FROM post');
$row = $res->fetch_object();
$count = $row->count;
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
StackSlave
  • 10,613
  • 2
  • 18
  • 35
  • That's not my edit. You should test for connection and `$res->num_rows`, free results, and even close the connection *(although, you could arguably avoid that last step)*. – StackSlave Feb 28 '18 at 00:07
  • You should NOT test for the connection (because, first, it is not the connection you are talking not about, but the query result; and second, you should NOT test for the query result either. Failing silently is a foul punch towards a fellow developer. You should always **let PHP tell you of the problem occurred**). Neither you should test for num_rows as it just makes no sense for this query. And yes, closing the connection is indeed could be used in some odd circumstances but definitely not in this script. – Your Common Sense Feb 01 '21 at 08:44