Skip to content
PHP Logo

What are the recommended methods for handling user input in PHP to prevent SQL injection vulnerabilities when executing MySQL commands?

To prevent SQL injection vulnerabilities when executing MySQL commands in PHP, it is recommended to use parameterized queries with prepared statements. This method ensures that user input is properly sanitized and treated as data rather than executable SQL code, thus preventing malicious SQL injection attacks.

php
// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare a SQL statement with a parameterized query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind user input to the prepared statement
$stmt->bind_param("s", $username);

// Set the user input
$username = $_POST['username'];

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

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

// Process the results as needed
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

// Close the statement and database connection
$stmt->close();
$mysqli->close();