Skip to content
PHP Logo

What are the potential risks of not properly escaping user inputs in PHP code when interacting with a MySQL database?

Not properly escaping user inputs in PHP code when interacting with a MySQL database can lead to SQL injection attacks, where malicious SQL queries are injected into the code. This can result in unauthorized access to the database, data manipulation, and potential data loss. To prevent this, user inputs should be properly sanitized and escaped before being used in SQL queries.

php
// Properly escaping user inputs in PHP code to prevent SQL injection
$user_input = $_POST['user_input']; // Example user input from a form

// Escaping user input before using it in a SQL query
$escaped_user_input = mysqli_real_escape_string($connection, $user_input);

// Using the escaped user input in a SQL query
$query = "SELECT * FROM users WHERE username = '$escaped_user_input'";
$result = mysqli_query($connection, $query);