Are there alternative methods in PHP to count occurrences of a specific string in MySQL data compared to substr_count()?

One alternative method to count occurrences of a specific string in MySQL data in PHP is to use SQL queries directly to retrieve the count. This can be achieved by using the SQL COUNT function along with a WHERE clause to filter for the specific string.

// Connect to MySQL 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);
}

// Define the specific string to count occurrences of
$searchString = "example";

// SQL query to count occurrences of the specific string in a specific column
$sql = "SELECT COUNT(*) AS count FROM table_name WHERE column_name LIKE '%$searchString%'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output the count of occurrences
    $row = $result->fetch_assoc();
    echo "Occurrences of '$searchString': " . $row["count"];
} else {
    echo "0 occurrences found.";
}

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