What is the significance of using mysql_real_escape_string() in PHP scripts to prevent SQL injections?
SQL injections occur when malicious SQL statements are inserted into input fields on a website, allowing attackers to manipulate the database. Using mysql_real_escape_string() in PHP scripts helps prevent SQL injections by escaping special characters in the input, making it safe to use in SQL queries.
// Connect to database
$conn = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Escape user input to prevent SQL injection
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// Query the database
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $sql);
// Rest of the code to handle the query result
Related Questions
- Are there any best practices or recommendations for structuring PHP code within variables to maintain readability and maintainability?
- What is the purpose of using the PHP session_start() function in the provided code?
- What is the best approach to sorting and displaying data in PHP based on different categories?