Using LIKE Queries in PDO
When trying to implement LIKE queries in PDO, you may encounter issues like the one described in the query below:
$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'"; $params = array($var1, $var2); $stmt = $handle->prepare($query); $stmt->execute($params);
This query will likely return no results, even when $var1 and $var2 contain valid search words. The error lies in the incorrect inclusion of % signs.
To correctly use LIKE in PDO, the % signs should be included in the $params array, not in the query itself. Here's the corrected code:
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?"; $params = array("%$var1%", "%$var2%"); $stmt = $handle->prepare($query); $stmt->execute($params);
By enclosing the variables in % signs within the $params array, you ensure that the % characters are substituted into the query correctly. Without this modification, the PDO prepared statement will treat the % signs as part of the literal string value, resulting in an incorrect query.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3