How can the use of deprecated PHP functions like mysql_connect be replaced with more secure alternatives like mysqli or PDO?

Using deprecated PHP functions like mysql_connect can pose security risks as they are no longer supported and may have vulnerabilities. To replace them with more secure alternatives like mysqli or PDO, you can update your code to use these newer functions which offer improved security features and better support for modern databases.

// Using mysqli
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Using PDO
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}