In the context of PHP, what are the differences between using mysql_real_escape_string and mysqli for database interactions, and what are the potential security implications of each?
When interacting with a database in PHP, it is important to sanitize user input to prevent SQL injection attacks. Using `mysql_real_escape_string` is deprecated in newer versions of PHP and should be replaced with `mysqli` functions, which provide improved security and support for prepared statements. `mysqli_real_escape_string` should be used to escape user input before including it in SQL queries to prevent malicious input from affecting the query execution.
// Establish a connection to the database using mysqli
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Escape user input using mysqli_real_escape_string
$user_input = mysqli_real_escape_string($mysqli, $_POST['user_input']);
// Use the sanitized user input in a SQL query
$query = "SELECT * FROM users WHERE username = '$user_input'";
$result = $mysqli->query($query);
// Process the query result
if ($result->num_rows > 0) {
// Output data
while($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"] . "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$mysqli->close();