Home  >  Article  >  Backend Development  >  How to Use Wildcards with PDO Prepared Statements: Why bindParam() Fails and How to Use bindValue() or Pre-Formatted Strings?

How to Use Wildcards with PDO Prepared Statements: Why bindParam() Fails and How to Use bindValue() or Pre-Formatted Strings?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 19:29:30844browse

How to Use Wildcards with PDO Prepared Statements: Why bindParam() Fails and How to Use bindValue() or Pre-Formatted Strings?

Using Wildcards with PDO Prepared Statements

Executing SQL queries with wildcards using PDO (PHP Data Objects) prepared statements can be challenging. This article addresses the issue and provides solutions.

The question presented involves finding all rows in the gc_users table with a wildcard in the name field, which can be expressed as:

<code class="sql">SELECT * FROM `gc_users` WHERE `name` LIKE '%anyname%';</code>

When attempting to execute this query using prepared statements, two unsuccessful approaches were taken:

<code class="php">$stmt = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` LIKE :name");
$stmt->bindParam(':name', "%" . $name . "%");
$stmt->execute();

$stmt = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` LIKE '%:name%'");
$stmt->bindParam(':name', $name);
$stmt->execute();</code>

The preferred solution involves using bindValue() instead of bindParam():

<code class="php">$stmt = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` LIKE :name");
$stmt->bindValue(':name', '%' . $name . '%');
$stmt->execute();</code>

Alternatively, as suggested in the provided answer, bindParam() can also be used:

<code class="php">$name = "%$name%";
$query = $dbh->prepare("SELECT * FROM `gc_users` WHERE `name` like :name");
$query->bindParam(':name', $name);
$query->execute();</code>

These solutions demonstrate how to successfully use wildcards with PDO prepared statements.

The above is the detailed content of How to Use Wildcards with PDO Prepared Statements: Why bindParam() Fails and How to Use bindValue() or Pre-Formatted Strings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn