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 ;)
CodePudding user response:
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:
- You should use SUM(), otherwise you'll only rows count
- Since it's an aggregating query which always returns a single row, use queryFirstRow instead of query
- YOu should define an alias for SUM(nums), so it will be easier to retrieve data from the result array.
CodePudding user response:
What do I have to change so that I only get the entries from 2020?
$results = DB:: queryFirstRow(
"SELECT SUM(nums) as nums_sum FROM tablename WHERE idnr = %i_idnr AND YEAR(timestamp) = %t_yearnr",
['idnr' => '1234', 'yearnr' => 2020]
);
I got only the Feedback "Udefined variable $str in MeekroDB Class"
SOLVED: only change %t to %s