简体   繁体   中英

Could not search when special character is in the string using PHP and MySQL

I need to search value from table using Like keyword and while I am putting special character with text its not showing any result. I am explaining my query below.

$name="Henna*/"
$sname='%'.$name.'%'; 
$sql="select * from cn_user_login name like '".$sname."' order by login_id desc";

I am explaining my table below.

cn_user_login:

login_id       name                  status

 1             Heena Mohanty           1

 2            Heena raj                1

 3            Heena@                   1

 4            Heena*                   1

Here no search result is coming. Here I need no matter if any special character is there if it will match up to some/all letter the result should come.

You can try this.. Remove special characters

$name="Henna*/";
$sname = preg_replace('/[^A-Za-z0-9\-]/', '', $name);

$sql="select * from cn_user_login where name like '%".$sname."%' order by login_id desc";

try to replace using the regular expectation

$name = preg_replace('/[^A-Za-z0-9\-]/', '', $name);

or

 $name = preg_replace('/[^A-Za-z0-9\-\']/', '', $name);

if you know the character then use str_replace() function

$name = str_replace("your character", '', $name);

Better solution is to use prepared statements from PDO

You can just write:

$sql = 'select * from cn_user_login name like :param_name order by login_id desc';
$paramName = '%'.$name.'%';

$db = new PDO('dsn_string', 'user', 'password');
$stm = $db->prepare($sql);
$stm->execute([':param_name' => $paramName]);
$result = $stm->fetchAll();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM