-1

I have a MySQL DB with multiple rows and a column that contain some text, separated with comma.

For a quick idea, my DB look like this:

id tag
1 wordpress, psd , html
2 wordpress, html
3 wordpress
4 psd

Output need to be like this:

tag count
wordpress 3
psd 2
html 2

i try this

<?php
select tag, count(id) FROM tableee GROUP BY tag
?>

and i try this

<?php
$query = mysqli_query($con, "SELECT tag FROM tableee   ");   
$convert_to_array = explode(',' , $row['tag'] );
$key_value = explode('=>', $convert_to_array [2]);  
echo count($key_value );
?>

and i try this

<?php       
    $query = mysqli_query($con, "SELECT tag FROM tableee   ");
    
    while($row=mysqli_fetch_assoc($query))
    
    {           
        $array = explode(" " ,$row['tag']);
    
        $array2=array();
    
        for($i = 0; $i<count($array); $i++)
    
        {
            array_push($array2, $array[$i] );
        }   
        print_r(     count($array2)       ) ;
    }
?>  

this Problem is solved by nbk

<?php
$query = mysqli_query($con, "SELECT tag FROM tableee   ");
$array2=array();
while($row=mysqli_fetch_assoc($query))

{           
    $array = explode("," ,$row['tag']);

    

    for($i = 0; $i<count($array); $i++)

    {
        array_push($array2, trim ($array[$i]) );
    }   
    

}
$array3 = array_count_values($array2);
$array4 = array_keys($array3);
print_r(   $array4[0] ) ;
print_r( $array3[ $array4[0]]);
?>  

3 Answers3

1

You need to intialize the array2 before you start the while, else you add always a new array to it

to count array you need array_count_values

And also you need to trim the splitet data, to remove all leading and trailing spaces

Last to split you need a comma not a space

<?php
$query = mysqli_query($mysqli, "SELECT tag FROM tableee   ");
$array2=array();
while($row=mysqli_fetch_assoc($query))

{           
    $array = explode("," ,$row['tag']);

    

    for($i = 0; $i<count($array); $i++)

    {
        array_push($array2, trim ($array[$i]) );
    }   
    

}
$array3 = array_count_values($array2);
$array4 = array_keys($array3);
print_r(   $array4[0] ) ;
print_r( $array3[ $array4[0]]);
nbk
  • 45,398
  • 8
  • 30
  • 47
0

I'm not sure about your question but. You can do an explode of your row, and count the number of iteration.

    <?php
foreach($dataToCount as $dataToExplode){
      $explodeToCommas=explode(',',$dataToExplode);
      //To understand the function explode do:
       var_dump($explodeToCommas);
       //count every iteration
        $countIteration=count($explodeToCommas);
}
RONIN_FR
  • 26
  • 3
0

You can directly achieve this in MYSQL by using feature in MYSQL known as 'char_length'.

$query = mysqli_query($con, "SELECT   id,  tag, 
  (CHAR_LENGTH(tag) - CHAR_LENGTH(REPLACE(tag, ',', '')) + 1) as count 
FROM tableee   ");

while($row=mysqli_fetch_assoc($query))

{           
   echo '<td>'.$row ["id"].'</td>';

echo '<td>'.$row["count"].'</td>';  
    
}
Prakhar Gyawali
  • 527
  • 4
  • 18