What are some common syntax errors to watch out for when writing SQL queries in PHP using mysqli?
One common syntax error to watch out for when writing SQL queries in PHP using mysqli is forgetting to properly escape variables to prevent SQL injection attacks. To solve this issue, always use prepared statements with placeholders and bind parameters to ensure that user input is sanitized.
// Example of using prepared statements with mysqli to avoid SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a SQL query with placeholders
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
// Bind parameters to the placeholders
$stmt->bind_param("s", $username);
// Set the parameter values
$username = "john_doe";
// Execute the query
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();