Use Bound Parameters Multiple Times
In database programming, using bound parameters is crucial for preventing SQL injection attacks. However, developers often encounter an issue when trying to use the same parameter multiple times within a prepared statement.
Original Problem Statement
The original post discusses a scenario where a user wishes to implement a search engine that utilizes a UNION SELECT to fetch data from different tables, each with a different search criteria. The query contains several instances of a ":term" parameter, which is being bound to a prepared statement.
Solution: User-Defined Variables
The provided solution offers an alternative approach to using bound parameters multiple times. By utilizing MySQL User-Defined Variables, developers can simplify their code and improve readability:
Example Code
$sql = "SET @term = :term"; $stmt = $dbh->prepare($sql); $stmt->bindValue(":term", "%$term%", PDO::PARAM_STR); $stmt->execute(); $sql = "SELECT ... FROM table WHERE name LIKE @term OR number LIKE @term"; $stmt = $dbh->prepare($sql); $stmt->execute(); $stmt->fetchAll();
Advantages
Downsides
The above is the detailed content of How Can I Reuse Bound Parameters Multiple Times in a Prepared Statement?. For more information, please follow other related articles on the PHP Chinese website!