What is the recommended method to count the occurrences of a specific value in a MySQL database using PHP?

To count the occurrences of a specific value in a MySQL database using PHP, you can execute a SQL query with the COUNT() function to retrieve the number of rows that contain the specific value. You can use a prepared statement to prevent SQL injection attacks and bind the specific value as a parameter in the query.

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

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

// Define the specific value to count
$specificValue = "example";

// Prepare the SQL query
$stmt = $mysqli->prepare("SELECT COUNT(*) FROM table_name WHERE column_name = ?");
$stmt->bind_param("s", $specificValue);

// Execute the query
$stmt->execute();

// Bind the result
$stmt->bind_result($count);

// Fetch the result
$stmt->fetch();

// Output the count
echo "Occurrences of specific value: " . $count;

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