How can the use of mysqli_ functions improve the security and efficiency of PHP code when working with databases?

Using mysqli_ functions instead of the older mysql_ functions can improve the security and efficiency of PHP code when working with databases. mysqli_ functions support parameterized queries, which help prevent SQL injection attacks. Additionally, mysqli_ functions offer better error handling and support for transactions, making database operations more reliable.

// Connect to the database using mysqli
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Example of executing a parameterized query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$username = "john_doe";
$stmt->execute();
$result = $stmt->get_result();

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

// Close the statement and connection
$stmt->close();
$mysqli->close();