Multiple Uses of Bound Parameters
In creating a basic database search engine, developers may encounter the need to include different types of information and retrieve data from multiple tables. When using prepared statements with bound parameters for pattern matching, the PDO documentation cautions against using the same named parameter marker more than once.
To bypass this limitation, one potential solution is to replace each :term parameter with :termX (where X represents term = n ). However, this can become cumbersome and error-prone.
An alternative approach is to utilize MySQL User-Defined Variables. By storing parameters in these variables, the code becomes more readable and avoids the need for additional PHP functions. Here's how it works:
Example:
$sql = "SET @term = :term"; try { $stmt = $dbh->prepare($sql); $stmt->bindValue(":term", "%$term%", PDO::PARAM_STR); $stmt->execute(); } catch (PDOException $e) { // error handling } $sql = "SELECT ... FROM table WHERE name LIKE @term OR number LIKE @term"; try { $stmt = $dbh->prepare($sql); $stmt->execute(); $stmt->fetchAll(); } catch (PDOException $e) { // error handling }
Advantages of User-Defined Variables:
Consideration:
An additional MySQL query is required, which may need to be taken into account for performance concerns.
The above is the detailed content of How Can I Efficiently Use Multiple Bound Parameters in MySQL Prepared Statements for Pattern Matching?. For more information, please follow other related articles on the PHP Chinese website!