PHP script to count comma-separated records [duplicate]

-1

In the database I have a column that receives strings in this format: ["87", "12", "67"]

What I need is to count each value separated by a comma and assign it to some variable, remembering that there are more rows. In this case I would have a variable with a value of 3.

My code has not evolved much, but I believe this is the path:

$conexao = mysqli_connect('localhost','root','');

$banco = mysqli_select_db($conexao,'bd');

mysqli_set_charset($conexao,'utf8');

$res = mysqli_query($conexao,"SELECT  replace(replace(coluna,'[',''),']','') FROM tabela");

$var = array($res);

echo count($var);

I count on the help of the community.

    
asked by anonymous 04.10.2018 / 22:42

1 answer

3

The format ["87","12","67"] is a valid JSON format, so you can use json_decode .

$conexao = mysqli_connect('localhost','root','');
$banco = mysqli_select_db($conexao,'bd');
mysqli_set_charset($conexao,'utf8');

$res = mysqli_query($conexao,"SELECT coluna FROM tabela");

while($r = mysqli_fetch_assoc($res)) { 
      echo "Quantidade: ". count(json_decode($r['coluna'], true));
}
    
04.10.2018 / 22:51