How important is escaping and sanitizing input data in PHP when executing MySQL queries?
Escaping and sanitizing input data in PHP when executing MySQL queries is crucial to prevent SQL injection attacks. By properly escaping user input, you can ensure that malicious SQL commands are not injected into your queries, protecting your database from potential security vulnerabilities.
// Example of escaping and sanitizing input data in PHP when executing MySQL queries
$mysqli = new mysqli("localhost", "username", "password", "database");
// Escape user input to prevent SQL injection
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// Prepare and execute the query with the sanitized input
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $mysqli->query($query);
// Process the query result
if ($result->num_rows > 0) {
// User authentication successful
} else {
// User authentication failed
}
$mysqli->close();