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

Linda Hamilton
Release: 2024-10-29 19:29:30
Original
843 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!