php mysqli prepared statement LIKE

前端 未结 2 730
时光说笑
时光说笑 2020-11-22 06:53

How can I with mysqli make a query with LIKE and get all results?

This is my code but it dosn\'t work:

$param = \"%{$_POST[\'user\']}%\";
$stmt = $db         


        
2条回答
  •  滥情空心
    2020-11-22 07:22


    Updated

    From comments it is found that LIKE wildcard characters (_and %) are not escaped by default on Paramaterised queries and so can cause unexpected results.

    Therefore when using "LIKE" statements, use this 'negative lookahead' Regex to ensure these characters are escaped :

    $param = preg_replace('/(?

    As an alternative to the given answer above you can also use the MySQL CONCAT function thus:

    $stmt = $db->prepare("SELECT id,Username FROM users WHERE Username LIKE CONCAT('%',?,'%') ");
    $stmt->bind_param("s", $param);
    $stmt->execute();
    

    Which means you do not need to edit your $param value but does make for slightly longer queries.

提交回复
热议问题