Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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  |
| 6612    |  43     |  2021-07-19 12:59:22  |
| 4565    |  31     |  2021-11-19 13:59:22  |
+---------+---------+-----------------------+

The SQL string:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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 😉

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading