Skip to content
Advertisement

SELECT COUNT with meekrodb Uncaught MeekroDBException

I would like to count the number of nums in a table from the associated idnr. However, I get the following error message: Fatal error: Uncaught MeekroDBException: If you use named args, you must pass an assoc array of args!

The table looks like this:

+---------+---------+-----------------------+
| idnr    |  nums   |  timestamp            |
+---------+---------+-----------------------+
| 1234    |  75     |  2021-10-19 11:59:22  |
| 1234    |  73     |  2021-11-09 11:59:22  |
| 1234    |  43     |  2020-07-19 12:59:22  |
| 4565    |  31     |  2021-11-19 13:59:22  |
+---------+---------+-----------------------+

The SQL string:

$results = DB::query("SELECT COUNT(nums) FROM tablename WHERE idnr = %i_idnr", '1234');

And I want to show it like:

echo $results['nums']; // the result should be 148

Thanks a lot 😉

Advertisement

Answer

Well, your error describes itself.

From the MeekroDB docs:

You can pass an array of named parameters and access them by name.

Example code:

DB::query("SELECT * FROM tbl WHERE name=%s_name AND age > %i_age AND height <= %d_height", 
  [
    'name' => $name,
    'age' => 15,
    'height' => 13.75
  ]
);

So in your case it would be:

$results = DB:: queryFirstRow(
    "SELECT SUM(nums) as nums_sum FROM tablename WHERE idnr = %i_idnr",
    ['idnr' => '1234']
);

echo $results['nums_sum'];

A few more notes:

  1. You should use SUM(), otherwise you’ll only rows count
  2. Since it’s an aggregating query which always returns a single row, use queryFirstRow instead of query
  3. YOu should define an alias for SUM(nums), so it will be easier to retrieve data from the result array.
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement