When handling SQL queries in PHP, what security measures should be taken to prevent SQL injection vulnerabilities, such as using mysqli_real_escape_string for input sanitization?
SQL injection vulnerabilities can be prevented by properly sanitizing user input before using it in SQL queries. One common method is to use mysqli_real_escape_string to escape special characters in the input. This function helps prevent malicious SQL queries from being executed by treating input as data rather than executable code.
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Sanitize user input using mysqli_real_escape_string
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$password = mysqli_real_escape_string($mysqli, $_POST['password']);
// Prepare SQL statement with sanitized input
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
// Execute the query
$result = $mysqli->query($sql);
// Handle the result
if ($result->num_rows > 0) {
// User authenticated successfully
} else {
// Invalid credentials
}
// Close the connection
$mysqli->close();
Related Questions
- What is the purpose of using a dynamic Pulldown in a PHP form?
- In PHP, what are the potential risks of using string interpolation with variable assignments in fwrite statements?
- What best practices should be followed when working with sessions in PHP, especially in relation to storing and retrieving data?