What are the recommended methods for sanitizing and escaping user input before using it in SQL queries in PHP?
When working with user input in SQL queries in PHP, it is crucial to sanitize and escape the input to prevent SQL injection attacks. One recommended method is to use prepared statements with parameterized queries, which automatically handle escaping and sanitizing input values. Another approach is to use functions like mysqli_real_escape_string() to manually escape user input before incorporating it into SQL queries.
// Using prepared statements with parameterized queries
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
$results = $stmt->fetchAll();
// Manually escaping user input using mysqli_real_escape_string()
$username = mysqli_real_escape_string($conn, $_POST['username']);
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $sql);