PDO Prepared Statements with Wildcard Support
Prepared statements offer improved security and performance for database queries by preventing SQL injection attacks. However, using wildcards with prepared statements can pose challenges.
In your case, you were trying to execute a query like:
<code class="sql">SELECT * FROM `gc_users` WHERE `name` LIKE '%anyname%'</code>
You attempted to bind the parameter with '%:name%' and ':name' methods, but both failed. Here's how you can use wildcards with prepared statements:
Using bindValue:
You can use bindValue to bind the wildcard parameters correctly:
<code class="php">$stmt = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` LIKE :name"); $stmt->bindValue(':name', '%' . $name . '%'); $stmt->execute();</code>
Using bindParam (Modified):
Additionally, you can also use bindParam with a slight modification:
<code class="php">$name = "%$name%"; $query = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` like :name"); $query->bindParam(':name', $name); $query->execute();</code>
The above is the detailed content of How to Use Wildcards with PDO Prepared Statements: A Guide to Avoiding Common Pitfalls?. For more information, please follow other related articles on the PHP Chinese website!