How can SQL injection vulnerabilities be mitigated when using user input in a SQL query in PHP?
SQL injection vulnerabilities can be mitigated by using prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This approach separates the SQL query logic from the user input data and prevents malicious SQL code from being executed.
// 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 user input data
$username = $_POST['username'];
// Execute the prepared statement
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();