What are the alternatives to using mysql_query to count entries in multiple tables in PHP, and how do they compare in terms of efficiency and accuracy?

When needing to count entries in multiple tables in PHP, using mysql_query is not recommended due to security risks and deprecated features. Instead, it is recommended to use prepared statements with parameter binding to ensure security and efficiency. This approach also allows for better handling of errors and prevents SQL injection attacks.

<?php

// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Prepare statement
$stmt = $conn->prepare("SELECT COUNT(*) FROM table1");
$stmt->execute();
$stmt->bind_result($count1);
$stmt->fetch();
$stmt->close();

$stmt2 = $conn->prepare("SELECT COUNT(*) FROM table2");
$stmt2->execute();
$stmt2->bind_result($count2);
$stmt2->fetch();
$stmt2->close();

echo "Count of entries in table1: " . $count1 . "<br>";
echo "Count of entries in table2: " . $count2 . "<br>";

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