Home >Database >Mysql Tutorial >How to Pass an Array of PDO Parameters with a LIMIT Clause?
In PDO, executing a query with a LIMIT clause using an array of parameters can be a challenge.
Consider the following code:
$sql = "SELECT * FROM table WHERE id LIKE CONCAT('%', :id, '%') LIMIT :limit1, :limit2"; $stmt = $pdo->prepare($sql); $stmt->execute($array); // Doesn't work
While it's desirable to use array input for convenience, the :limit1 and :limit2 parameters won't work unless they are bound individually:
$stmt->bindParam(':limit1', $limit1, PDO::PARAM_INT); $stmt->bindParam(':limit2', $limit2, PDO::PARAM_INT); $stmt->execute(); // Still doesn't work
The problem lies in PDO's default setting of PDO::ATTR_EMULATE_PREPARES to true. This setting causes PHP to emulate prepared statements instead of using native MySQL prepared statements, which prevents the proper binding of LIMIT parameters.
To resolve this issue, disable emulation by setting the attribute to false:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Once emulation is disabled, the array input can be used to execute the query correctly:
$stmt = $pdo->prepare($sql); $stmt->execute($array); // Works!
Note that disabling emulation may have a performance impact, as native prepared statements are more efficient in certain scenarios. However, for queries that require dynamic LIMIT clauses, it's the most reliable solution.
The above is the detailed content of How to Pass an Array of PDO Parameters with a LIMIT Clause?. For more information, please follow other related articles on the PHP Chinese website!