What are best practices for validating and escaping user input in PHP to prevent SQL injection attacks?

To prevent SQL injection attacks in PHP, it is crucial to validate and escape user input before using it in database queries. This can be achieved by using parameterized queries with prepared statements or by using functions like mysqli_real_escape_string() to escape user input. It is also important to sanitize and validate input data to ensure that only expected values are passed to the database.

// Example of using prepared statements to prevent SQL injection

// Establish a database connection
$connection = new mysqli("localhost", "username", "password", "database");

// Validate and sanitize user input
$username = $_POST['username'];
$password = $_POST['password'];

// Prepare a SQL query using a prepared statement
$stmt = $connection->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);

// Execute the query
$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();
$connection->close();