Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue with searching for special characters % and _ #814

Open
jeffersonsalvador opened this issue Nov 26, 2024 · 0 comments
Open

Issue with searching for special characters % and _ #814

jeffersonsalvador opened this issue Nov 26, 2024 · 0 comments

Comments

@jeffersonsalvador
Copy link

Description:

Currently, when performing searches using the LIKE or ILIKE operator in MySQL, we are not correctly handling the special characters % and _, which are used as wildcards. These characters are interpreted by MySQL as wildcards, leading to unexpected results during searches.

Problem:
When the search value contains % or _, MySQL interprets these characters as wildcards, which can result in more records being returned than expected. This happens even when the user intends to search for the literal % or _ characters.

Example:

  • If a user searches for "20%", MySQL might interpret this as "any value starting with 20", leading to unexpected results.
  • The same issue occurs with the _, which represents any single character. If the user searches for "name_1" it also will retrieve "name01" or similar.

Proposed Solution:

To resolve this issue, we can use PHP's addcslashes() function to escape the % and _ characters before sending the query to MySQL. The addcslashes() function will add a backslash (\) before these special characters, ensuring that MySQL treats them as literals instead of wildcards.

Suggested Code Changes:

  • Before applying the search value to the LIKE or ILIKE operator, we should use addcslashes() to escape the % and _ characters.
if (isset($searchData[$field])) {
    $searchData[$field] = addcslashes($searchData[$field], '%_');
    $value = ($condition == "like" || $condition == "ilike") ? "%{$searchData[$field]}%" : $searchData[$field];
} else {
    if (!is_null($search) && !in_array($condition, ['in', 'between'])) {
        $search = addcslashes($search, '%_');
        $value = ($condition == "like" || $condition == "ilike") ? "%{$search}%" : $search;
    }
}

This ensures that % and _ are treated as literal characters rather than wildcards, providing more accurate search results.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant