What are some best practices for securing SQL queries in PHP to prevent SQL injection attacks?
SQL injection attacks can be prevented by using prepared statements and parameterized queries in PHP. This involves separating the SQL query from the user input data and binding parameters to the query before execution. By doing this, the input data is treated as data rather than executable code, making it impossible for attackers to inject malicious SQL code.
// 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 with 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();