Searching for LIKE, or CONTAINS. Moodle 2.9.3

Searching for LIKE, or CONTAINS. Moodle 2.9.3

by Dave Emsley -
Number of replies: 4

Hi There,

This should be obvious but my mind is blank.

Can I find all courses with "MATH" in the title?

In SQL it would be SELECT FROM courses WHERE fullname LIKE %MATH%  or SELECT FROM courses WHERE CONTAINS(fullname, '%MATH%')

Neither:

$course = $DB->get_record_sql('SELECT FROM {course} WHERE Contains(fullname , ? )' , array('%MATH%');

or

$course = $DB->get_record_sql('SELECT FROM {course} WHERE fullname LIKE ?)' , array('%MATH%');


work.

Any ideas gratefully received.

Best Regards

Dave



Average of ratings: -
In reply to Dave Emsley

Re: Searching for LIKE, or CONTAINS. Moodle 2.9.3

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

$sql = 'SELECT FROM {course} WHERE '.$DB->sql_like('fullname', ':value', false); // false = not case sensitive.

$params = ['value' => '%math%'];

$DB->get_record_sql($sql, $params);


Average of ratings: Useful (1)
In reply to Dave Emsley

Re: Searching for LIKE, or CONTAINS. Moodle 2.9.3

by Michael Aherne -
Picture of Core developers Picture of Peer reviewers Picture of Plugin developers

Do you have debugging switched on? Neither of those lines is valid PHP syntax so you're probably getting a fatal error. I'd expect something like the second one to work but it's missing the field list in the SQL and there's a rogue parenthesis at the end.

Something like this should work:

$course = $DB->get_record_sql('SELECT * FROM {course} WHERE fullname LIKE ?' , array('%MATH%'));
but if you need cross-database compatibility you might be better off using the sql_like() method:

$course = $DB->get_record_sql('SELECT * FROM {course} WHERE ' . $DB->sql_like('fullname', '?'), array('%MATH%'));
or even just
$course = $DB->get_record_select('course', $DB->sql_like('fullname', '?'), array('%MATH%'));

Average of ratings: Useful (1)
In reply to Dave Emsley

Re: Searching for LIKE, or CONTAINS. Moodle 2.9.3

by Darko Miletić -

This would work:

$rec = $DB->get_records_select(
'course',
$DB->sql_like('fullname', ':within', false, false),
['within' => '%algebra%']
);

And this as well:

$rec = $DB->get_records_sql(
"SELECT * FROM {course} WHERE ".$DB->sql_like('fullname', ':within', false, false),
['within' => '%algebra%']
);

Average of ratings: Useful (1)