What are the benefits of using MySQLi or PDO over mysql_* functions in PHP for database operations?
Using MySQLi or PDO over mysql_* functions in PHP for database operations is recommended because mysql_* functions are deprecated as of PHP 5.5.0 and removed in PHP 7. Additionally, MySQLi and PDO offer better security features such as prepared statements to prevent SQL injection attacks. They also provide better support for newer MySQL features and are more object-oriented, making them easier to work with in the long run.
// Using MySQLi for database operations
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * FROM users";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
$mysqli->close();