Skip to content
PHP Logo

How can PHP developers securely handle user input when interacting with a MySQL database?

PHP developers can securely handle user input when interacting with a MySQL database by using prepared statements and parameterized queries. This helps prevent SQL injection attacks by separating SQL code from user input data. By binding parameters to placeholders in the SQL query, developers can ensure that user input is treated as data rather than executable code.

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

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

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

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

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

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Handle the retrieved data
}

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