What are the best practices for handling database connections and queries in PHP to avoid deprecated functions like mysql_*?

When handling database connections and queries in PHP, it is important to avoid using deprecated functions like mysql_* as they are no longer supported in newer versions of PHP. Instead, you should use MySQLi or PDO extensions for interacting with databases. This will not only ensure compatibility with future PHP versions but also provide better security and performance.

// Using MySQLi extension to connect to a database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Perform a query using prepared statements
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

$username = "john_doe";
$stmt->execute();

$result = $stmt->get_result();

// Fetch results
while ($row = $result->fetch_assoc()) {
    echo "Username: " . $row["username"];
}

// Close connection
$stmt->close();
$conn->close();