How can SQL injection attacks be prevented when using integers in MySQL queries in PHP?

SQL injection attacks can be prevented when using integers in MySQL queries in PHP by using prepared statements with bound parameters. This ensures that user input is treated as data rather than executable SQL code, thereby preventing malicious SQL injection attempts.

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

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

// Bind the integer input to the parameter
$id = intval($_GET['id']);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

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

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