What are the recommended alternatives to the mysql_* functions in PHP for database operations, and why are they preferred over the deprecated functions?
The recommended alternatives to the deprecated mysql_* functions in PHP for database operations are either MySQLi (MySQL Improved) or PDO (PHP Data Objects). These alternatives provide better security, support for prepared statements, and are more versatile in terms of database support. It is important to switch to these alternatives to ensure compatibility with newer versions of PHP and to follow best practices for database interactions.
// Using MySQLi for database operations
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Perform database operations using prepared statements
$stmt = $mysqli->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row['id'] . " Name: " . $row['name'] . "<br>";
}
$stmt->close();
$mysqli->close();