0

I am a newbie to PHP. I want to count the occurrence of a specific word in a MySQL db row. For example: There are two columns name and description.

---------------------------------------------------------------
| name | description                                          |
---------------------------------------------------------------
| abcd | My name ***is*** abcd. My father's name ***is*** xyz |
---------------------------------------------------------------
| xyzt | My name ***is*** xyz. I am a good girl.              |
---------------------------------------------------------------

I want to count the occurrence of the word 'is' from the 1st row description column. In the above example, 'is' occurs twice in the 1st row and once in the second row. Please guide me for the same.

Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43
user3732838
  • 11
  • 1
  • 2
  • For a SQL only answer, please see http://stackoverflow.com/questions/12344795/count-the-number-of-occurences-of-a-string-in-a-varchar-field – Fluffeh Jun 12 '14 at 12:13
  • 1
    NOT voting to close this as a duplicate of the question linked above, since that question asks about strings while this question explicitly asks about *words* – symcbean Jun 12 '14 at 12:21
  • Try `select count(*) from yourtable where match(description) against ('is');` borrowed from http://stackoverflow.com/a/396266/ or `select count(*) from table where fieldname REGEXP '[[:<:]]word[[:>:]]';` from http://stackoverflow.com/a/395859/ – Funk Forty Niner Jun 12 '14 at 12:39

4 Answers4

2

There are plenty of pure-SQL attempted solutions here on StackOverflow, but most of them count strings, not words. So let's reiterate:

SQL in general, and MySQL in particular, is not the best fit for the job. You'd better do it with PHP (if the result set is "small enough"):

$count = preg_match_all("/\\b$word\\b/", $input, &$matches);

Alternative, richer solutions exist based on str_word_count().

Note that it can be achieved in pure SQL:

  • with a stored procedure like this one.

    In this example, replace the regex with [[:<:]]your_word[[:>:]] to match a specific word. Then just SELECT wordcount(your_column) FROM your_table. Improve the procedure by adding an input paramter (the word to count occurrences of). Then* RLIKE CONCAT('[[:<:]]', input_parameter, '[[:>:]]').

  • even without a stored procedure (but with the help of an auxiliary table).

    In this example, replace HAVING word <> ' ' with HAVING word <> 'your_word' to count a specific word. GROUP BY word, maintable.id (instead of just word) to get a detailed cound by row. Add WHERE clauses to filter out the rows. Drawback: only a spaces are recognised as word delimiters.

I suppose the benefit of going for a PHP-based solution is obvious.

Community
  • 1
  • 1
RandomSeed
  • 29,301
  • 6
  • 52
  • 87
1

Query for this:

SELECT name,(CHAR_LENGTH(description)-
        CHAR_LENGTH(REPLACE(description,'is','')))/CHAR_LENGTH('is') AS TotalCount
FROM TableName
GROUP BY name

Result:

NAME    TOTALCOUNT
abcd    2
xyzt    1

Fiddle Demo

EDIT:

Since this query also counts any words which contains is (like 'this'), we can query for ' is ' (with one space before and one after).

SELECT name,(CHAR_LENGTH(description)-
        CHAR_LENGTH(REPLACE(description,' is ','')))/CHAR_LENGTH(' is ') AS TotalCount
FROM TableName
GROUP BY name
Raging Bull
  • 18,593
  • 13
  • 50
  • 55
0

Try using substr_count:

substr_count ( string $haystack , string $needle)

It counts the amount of occurrences of a word in a string.

robinp7720
  • 443
  • 4
  • 12
0

Pass all rows in array :

$query= "SELECT * from  yourtable "; 
$result= $mysqli->query($query);
while ($row = mysqli_fetch_assoc($result)) {
$rows[]=$row;
}

And transform array in array with count :

foreach ($rows as $row){
$name=$row['name'];
$description=$row['description'];
$myarr[$name]=substr_count($description, 'is');
}

You obtain desired array :

abcd => 2
xyzt => 1
...