What are the potential pitfalls of using arrays in MySQL queries in PHP?
Using arrays in MySQL queries in PHP can lead to SQL injection vulnerabilities if the array values are not properly sanitized or escaped. To prevent this, it is recommended to use prepared statements with parameterized queries instead of directly inserting array values into the query.
// Example of using prepared statements with parameterized queries to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a query with a placeholder for the array value
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column = ?");
$value = "example_value";
// Bind the array value to the placeholder
$stmt->bind_param("s", $value);
// Execute the query
$stmt->execute();
// Fetch the results
$result = $stmt->get_result();
// Output the results
while ($row = $result->fetch_assoc()) {
echo $row['column_name'] . "<br>";
}
// Close the statement and connection
$stmt->close();
$mysqli->close();