What you describe can be done via MySQL without recourse to PHP.
Given the way you have records, my suggestion is to use a temporary table to insert a record for each value that is separated by a comma and then select from that temporary table with the count:
Simulate your table:
CREATE TABLE minhaTabela
('id' int, 'nome' varchar(100), 'tags' varchar(255))
;
INSERT INTO minhaTabela
('id', 'nome', 'tags')
VALUES
(1, "Gabe♦", 'Php, Mysql, Java'),
(2, "bfavaretto♦", 'MYSQL, Apostila, Java'),
(3, "utluiz♦", 'Microsoft, C++, Java'),
(3, "John", 'C++, Apostila, Java'),
(3, "Doe", 'Apostila, Mysql, Java')
;
Pass values to a temporary table:
CREATE TEMPORARY TABLE temp (val CHAR(255));
SET @S1 = CONCAT("INSERT INTO temp (val) VALUES ('",REPLACE((SELECT GROUP_CONCAT( DISTINCT 'tags') AS data FROM 'minhaTabela'), ",", "'),('"),"');");
PREPARE stmt1 FROM @s1;
EXECUTE stmt1;
Select the words and count the number of occurrences:
SELECT val, count(*) FROM temp GROUP BY LOWER(TRIM(val));
Result obtained:
SQL Fiddle
┌───────────┬──────────┐
│ val │ count(*) │
├───────────┼──────────┤
│ Apostila │ 3 │
├───────────┼──────────┤
│ C++ │ 2 │
├───────────┼──────────┤
│ Java │ 5 │
├───────────┼──────────┤
│ Microsoft │ 1 │
├───────────┼──────────┤
│ Mysql │ 3 │
├───────────┼──────────┤
│ Php │ 1 │
└───────────┴──────────┘
To use on the PHP side using PDO:
/* Dados da ligação à base de dados
*/
$dbcon = array(
"host" => 'localhost',
"dbname" => 'minhaBaseDados',
"username" => 'utilizador',
"password" => 'password'
);
/* Ligar à base de dados
*/
$dbh = new PDO(
'mysql:host='.$dbcon['host'].';dbname='.$dbcon['dbname'].';',
$dbcon['username'],
$dbcon['password'],
array(
PDO::ATTR_PERSISTENT => false,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
)
);
/* Ler os dados para uma tabela temporária
*/
$sql = "
CREATE TEMPORARY TABLE temp (val CHAR(255));
SET @S1 = CONCAT(\"INSERT INTO temp (val) VALUES ('\",REPLACE((SELECT GROUP_CONCAT( DISTINCT 'tags') AS data FROM 'minhaTabela'), \",\", \"'),('\"),\"');\");
PREPARE stmt1 FROM @s1;
EXECUTE stmt1";
$sth = $dbh->prepare($sql);
$sth->execute();
$sth->closeCursor();
/* Recolher a informação
*/
$sth = $dbh->query("SELECT val, count(*) AS total FROM temp GROUP BY LOWER(TRIM(val))");
$sth->setFetchMode(PDO::FETCH_OBJ);
while ($row = $sth->fetch()) {
echo '<p>A palavra '.$row->val.' está repetida '.$row->total.' '.($row->total==1?'vez':'vezes').'.</p>';
}
/* Matar a ligação e o script
*/
$dbh = null;
die();