What are the recommended alternatives to using the deprecated mysql_* functions in PHP for database operations?
The recommended alternatives to using the deprecated mysql_* functions in PHP for database operations are to use either MySQLi (MySQL Improved) or PDO (PHP Data Objects). Both MySQLi and PDO offer more secure and feature-rich options for interacting with databases in PHP.
// Using MySQLi
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
}
$result = $mysqli->query("SELECT * FROM table");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row['id'] . " Name: " . $row['name'] . "<br>";
}
} else {
echo "No results found";
}
$mysqli->close();