In what scenarios would using mysqli or mysql_real_escape_string be preferable over PDOs for database interactions in PHP?
When dealing with legacy code or existing projects that heavily rely on the mysqli extension or mysql_real_escape_string function, it may be preferable to continue using them for consistency and compatibility reasons. Additionally, if you are working on a small project and do not want to introduce the complexity of PDO, using mysqli or mysql_real_escape_string can be a simpler solution.
// Using mysqli for database interactions
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
}
$name = mysqli_real_escape_string($mysqli, $_POST['name']);
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
$mysqli->close();
Related Questions
- What does the "modulo" function do in PHP and how can it be used for alternating row colors?
- What is the recommended method to convert a double price to an integer in PHP?
- What are some best practices for organizing and structuring PHP code to improve readability and maintainability when working with XML files?