You can use an array in a MySQLi query in PHP by using a prepared statement with parameter binding. Here's an example:
$values = array('John', 'Doe', 'johndoe@example.com');
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
exit();
}
$query = "INSERT INTO users (first_name, last_name, email) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $values[0], $values[1], $values[2]);
$stmt->execute();
if ($stmt->affected_rows == 0) {
echo "Error executing query: " . $mysqli->error;
exit();
}
$stmt->close();
$mysqli->close();
In this example, we create an array of values to use in the query ($values). We then use a prepared statement to insert these values into a MySQL database. The bind_param method binds the values from the array to the placeholders in the SQL statement.
Note that the first argument to bind_param specifies the types of the parameters. In this case, we're using three strings ("sss") because our values are strings. If we were using integers or other data types, we would use a different type specifier (such as "iii" for three integers).
This approach is useful for preventing SQL injection attacks, as the values are properly escaped and sanitized by the prepared statement. It also allows for better performance when executing multiple similar queries with different values, as the prepared statement can be reused with different parameter bindings.