What are common pitfalls when writing SQL queries in PHP?
One common pitfall when writing SQL queries in PHP is not properly sanitizing user input, which can leave your application vulnerable to SQL injection attacks. To solve this issue, always use prepared statements with parameterized queries to securely pass user input to the database.
// Example of using prepared statements to prevent SQL injection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare a SQL query using a parameterized statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set parameters and execute the query
$username = $_POST['username'];
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process each row
}
// Close the statement and connection
$stmt->close();
$conn->close();