How can the use of mysql_real_escape_string function prevent SQL injection attacks in PHP scripts?
SQL injection attacks occur when user input is not properly sanitized, allowing malicious SQL queries to be executed. Using the mysql_real_escape_string function in PHP helps prevent SQL injection by escaping special characters in user input before it is used in a SQL query. This function ensures that any malicious characters are treated as literal characters, rather than executable SQL code.
// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check if the connection is successful
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Sanitize user input using mysql_real_escape_string
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
// Use the sanitized input in a SQL query
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $query);
// Process the query result
if (mysqli_num_rows($result) > 0) {
// User authentication successful
} else {
// User authentication failed
}
// Close the database connection
mysqli_close($connection);
Related Questions
- What is the best practice for evaluating the return value of mysql_query() in PHP?
- What are the potential pitfalls of using the same name attribute for form elements generated within a foreach loop in PHP?
- What are the best practices for creating abstract methods in PHP classes for database interactions?