How can PHP developers securely pass user IDs as variables in SQL queries to prevent SQL injection attacks?

To securely pass user IDs as variables in SQL queries to prevent SQL injection attacks, PHP developers should use prepared statements with parameterized queries. This method separates the SQL query logic from the user input, preventing malicious input from altering the query structure.

// Assuming $userID contains the user ID to be passed in the query
$userID = $_GET['userID'];

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

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :userID");

// Bind the user ID variable to the prepared statement
$stmt->bindParam(':userID', $userID);

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

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