How can SQL injection vulnerabilities be mitigated when passing variables through URLs in PHP?

SQL injection vulnerabilities can be mitigated by using prepared statements and parameterized queries when interacting with the database. This ensures that user input is properly sanitized and treated as data rather than executable SQL code.

// Example of using prepared statements to mitigate SQL injection in PHP

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// User input from URL parameter
$user_id = $_GET['user_id'];

// Prepare a SQL statement with a placeholder for the user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :user_id");

// Bind the user input to the placeholder
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}