Home >Backend Development >PHP Tutorial >How to Correctly Bind an Array of Strings to a MySQLi Prepared Statement?
Binding an Array of Strings with a mysqi Prepared Statement
When working with MySQL, it's often necessary to bind an array of values to a WHERE IN clause using a prepared statement. While this task may seem straightforward, there are a few potential pitfalls that can lead to errors.
In this article, we'll explore the correct approach to binding an array of strings using mysqli prepared statements. We'll also provide a detailed explanation of the steps involved and discuss a potential solution.
What's Going Wrong?
The code sample provided in the question incorrectly attempts to bind an array of cities to a prepared statement using bind_param. However, bind_param expects scalar values (e.g., strings, integers, etc.) as its arguments. Attempting to bind an array directly will result in an error.
The Correct Approach
To successfully bind an array of strings to a prepared statement, we can use the following steps:
Example Code
Here's an example of the correct code:
$mysqli = new mysqli("localhost", "root", "root", "db"); if(!$mysqli || $mysqli->connect_errno) { return; } $cities = explode(",", $_GET['cities']); $in = str_repeat('?,', count($cities) - 1) . '?'; $query_str = "SELECT name FROM table WHERE city IN ($in)"; $query_prepared = $mysqli->stmt_init(); if($query_prepared && $query_prepared->prepare($query_str)) { $types = str_repeat('s', count($cities)); $query_prepared->bind_param($types, ...$cities); $query_prepared->execute(); }
In this example, we first create a string of placeholders using str_repeat. We then insert this placeholder string into the query and prepare the statement. Notice how we bind the individual elements of the cities array using ...$cities and specify the data type using str_repeat('s', count($cities)).
By following these steps, we can successfully bind an array of strings to a mysqli prepared statement and execute the query as intended.
The above is the detailed content of How to Correctly Bind an Array of Strings to a MySQLi Prepared Statement?. For more information, please follow other related articles on the PHP Chinese website!