2

I am trying to fetch the number of rows for a query using a Moodle function.

This is what I have done so far:

$records = $DB->get_records_sql("select * from {user} where maildigest=$login_id"); 

How do I get the number of results?

SUB0DH
  • 5,130
  • 4
  • 29
  • 46
user200
  • 291
  • 1
  • 4
  • 21

2 Answers2

3

You can use a Moodle specific function to count records:

$DB->count_records($table);

In your case you can use:

echo $DB->count_records('user', array('maildigest'=>$login_id));

This function has been designed to improve efficiency: you do not need to retrieve a whole bunch of data if you just want to count the retrieved records;-)

Aldo Paradiso
  • 911
  • 2
  • 15
  • 30
0

get_records_sql() retruns an array, so use count() to get number of records.

Do like below:-

$records=$DB->get_records_sql("select * from {user} where maildigest=$login_id");

echo (count($records));

Link section you have to refer:- https://prnt.sc/gpggq4

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
  • I would not recommend any solution that involves inserting arbitrary values into SQL statements like that - you are asking for SQL injection attacks. The answer by Aldo Paradiso, is the correct solution. – davosmith Sep 25 '17 at 14:28
  • @davosmith i don't think so, because his code is as much vulnerable as mine. `array('maildigest'=>$login_id)` will not insure `prevention`. BTW have no issue. Thanks – Alive to die - Anant Sep 26 '17 at 14:14
  • Yes it will, as Moodle DB functions will clean and escape every param added that way, simply using string insertion as shown here leaves you open to malicious SQL – davosmith Sep 26 '17 at 14:16
  • @AlivetoDie hii have one doubt – user200 Oct 16 '17 at 10:07
  • @user200 please ask a new question if you have any doubt. Thanks – Alive to die - Anant Oct 16 '17 at 10:22
  • i already asked..can you please look at that here is the link https://stackoverflow.com/questions/46765498/show-the-error-message-while-uploading-excel-file-data-in-db-if-user-already-exi/46765972?noredirect=1#comment80482745_46765972 – user200 Oct 16 '17 at 11:39