Skip to content
PHP Logo

How can SQL injection vulnerabilities be mitigated when using user-input IDs in MySQL queries in PHP?

SQL injection vulnerabilities can be mitigated by using prepared statements with parameterized queries in PHP when using user-input IDs in MySQL queries. This approach ensures that user input is treated as data rather than executable SQL code, preventing malicious SQL injection attacks.

php
// Assuming $conn is the MySQL database connection
$user_id = $_GET['user_id'];

$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    // Process the data
}

$stmt->close();
$conn->close();