How can SQL injection vulnerabilities be prevented when passing user input to MySQL queries in PHP?
SQL injection vulnerabilities can be prevented by using prepared statements in PHP when passing user input to MySQL queries. Prepared statements separate the SQL query logic from the user input, preventing malicious SQL code from being injected. This method parameterizes the query, ensuring that user input is treated as data rather than executable code.
// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a SQL query using a placeholder for the user input
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
// Bind the user input to the placeholder
$stmt->bind_param("s", $username);
// Set the user input
$username = $_POST['username'];
// Execute the query
$stmt->execute();
// Fetch the results
$result = $stmt->get_result();
// Process the results
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();