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('/(?<!\\\)([%_])/', '\\\$1',$param);
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();
PDO named placeholder version:
$stmt = $db->prepare("SELECT id,Username FROM users WHERE Username LIKE CONCAT('%',:var,'%') ");
$stmt->bind_param("s", ['var'=>$param]);
$stmt->execute();
Which means you do not need to edit your $param
value but does make for slightly longer queries.