In what ways can transitioning from mysql functions to MySQLi or PDO improve the reliability and security of PHP scripts that interact with databases?

Transitioning from mysql functions to MySQLi or PDO can improve the reliability and security of PHP scripts that interact with databases by offering prepared statements, parameterized queries, and improved error handling. These features help prevent SQL injection attacks, improve performance, and provide more robust database interaction capabilities.

// Using MySQLi
$mysqli = new mysqli("localhost", "username", "password", "database");

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

$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $username);
$username = "example";

$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    // Process the data
}

$stmt->close();
$mysqli->close();