How can deprecated mysql_* functions be replaced with more modern alternatives like PDO or mysqli_* in PHP code?
The deprecated mysql_* functions in PHP have been removed in newer versions of PHP. To replace them with more modern alternatives like PDO or mysqli_*, you need to update your code to use these newer functions. This involves rewriting your database queries using PDO or mysqli_* functions, which provide better security and performance.
// Using PDO to connect to a database
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
// Example query using PDO
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => 1]);
$user = $stmt->fetch();