Search code examples
phpsql-likemoodle

How to add like condition to existing query in moodle


I have a query with multiple conditions check. I want to add the condition to check the with like clause. I tried like this.

$params1['email'] =$DB->sql_like('email', '%'.$voucher_query.'%');

and I am passing the params1 value to query condition. I am getting the query as different and it is not working. This is the query I am getting.

SELECT COUNT('x') FROM tbl_order WHERE active_ind = ? AND id = ? AND email = ? [array ( 0 => 1, 1 => 236909, 2 => 'email LIKE %emelchor% COLLATE utf8_bin ESCAPE \'\\\\\'', )]

the email condition is checking with equals to but not with like exactly. Can anyone help me out.?

Thanks in advance


Solution

  • You haven't shown the function call you are doing to retrieve the records, but I'm guessing it looks something like:

    $DB->get_records('order', $params);
    

    This simple DB syntax is only suitable for equals comparisons, if you want to do something more complex, you will need to rewrite it to use the get_records_select function instead, e.g.

    $select = 'active_ind = :ind AND id = :id AND '.$DB->sql_like('email', ':email');
    $email = '%'.$DB->sql_like_escape($voucher_query).'%';
    $params = ['ind' => $ind, 'id' => $id, 'email' => $email];
    $result = $DB->get_records_select('order', $select, $params);