What are the best practices for handling database queries in PHP to avoid SQL injection vulnerabilities?
To avoid SQL injection vulnerabilities in PHP, it is essential to use prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, preventing malicious SQL code from being injected into the query. Additionally, input validation and sanitization should be implemented to further enhance security.
// Establish a database connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a SQL statement with a parameterized query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set the parameter values and execute the query
$username = $_POST['username'];
$stmt->execute();
// Process the query results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Handle the data retrieved from the database
}
// Close the statement and database connection
$stmt->close();
$mysqli->close();