0

I have this text string varchar type i get from database echo. how to extract it and count the value :

in the database it save as string ["1","2","3"] in varchar. how to count this as 3 item using php?

my sql code is :

$sql2 = "SELECT * FROM il_dcl_stloc1_value WHERE record_field_id = '$exc_prt_id'";
$result2 = $conn->query($sql2);

        while($row2 = $result2->fetch_assoc()) {
            $exc_prt_id1 = $row2['value'];
            echo "$exc_prt_id1"; // this will result ["1","2","3"]

}
2
  • I'm kind of hoping that means you're actually storing JSON, not generating that string? In which case you can json_decode it to an array and just call count. Commented Aug 1, 2019 at 12:49
  • 1) If you store JSON in MySQL use JSON datatype and not a string dataype like (VAR)CHAR|TEXT 2) Which MySQL version? As MySQL has native JSON parsing functions SELECT VERSION(); 3) Whats the reason of storing in JSON this simple array can really easy be normalized? Commented Aug 1, 2019 at 12:53

2 Answers 2

3

There are tons of ways you can do this, but if you just care about the count, not the values, and they will always come in this format, you can just use

$count = count(explode(",", $exc_prt_id1));

You can also do a

$count = count(json_decode($exc_prt_id1));

If you want the values, run the above code without the count.

$arr = json_decode($exc_prt_id1);

This will result in a PHP array.

While the 2nd option is generally preferred and is better practice, the 1st one might be of use in certain cases. If there is anything unclear, just ask :)

Sign up to request clarification or add additional context in comments.

Comments

0

Try this way

$exc_prt_id1= str_replace("[","",$exc_prt_id1);
$exc_prt_id1= str_replace("]","",$exc_prt_id1);
$exc_prt_id1= str_replace('"','',$exc_prt_id1);
$invoiceArr = explode(",",$exc_prt_id1);
$count = count(explode(",", $invoiceArr ));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.