PHP script for counting comma-separated records

Asked

Viewed 190 times

-2

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

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

My code hasn’t evolved much, but I believe this is the way:

$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.

1 answer

3


The format ["87","12","67"] is a valid JSON format, so you can use the 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));
}
  • 2

    +1, very simple and direct

Browser other questions tagged

You are not signed in. Login or sign up in order to post.