How can SQL injection vulnerabilities be prevented when writing PHP scripts for database operations?
SQL injection vulnerabilities can be prevented by using prepared statements and parameterized queries in PHP scripts for database operations. This helps to separate SQL code from user input, preventing malicious SQL queries from being executed.
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare a SQL statement using a parameterized query
$stmt = $conn->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 results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the statement and connection
$stmt->close();
$conn->close();