2

I need to count the number of elements that exist in the column of a MySQL database row for multiple rows and them add them all together. This is the code I used to count the number of array elements (which are numbers separated by commas):

$result = substr_count($count_fetch['micro_analysis'], ",") + 1;

But now I need to do this for each row, which could vary depending on the query. I need to add the $result of each row together to get a final sum of all the rows. I used the following code but I get the incorrect value, can someone please point me in the right direction?

$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";

      $count_query = mysqli_query($conn, $sql);
      $count_fetch = mysqli_fetch_assoc($count_query);

      foreach ($count_fetch as $row) {
         $result = substr_count($count_fetch['micro_analysis'], ",") + 1;
         $end_result += $result;

      }

      echo $end_result;
1
  • 3
    Can you not use MySQL COUNT() or SUM() functions to do the math for you? Commented Dec 10, 2018 at 9:55

2 Answers 2

1

You are just fetching 1 row and then trying to count over that row, instead you need to loop over the rows and add the fields in that...

  $sql = "SELECT * FROM samples_database WHERE order_id = $order_id";

  $end_result = 0;
  $count_query = mysqli_query($conn, $sql);
  while( $row = mysqli_fetch_assoc($count_query)) {
     $end_result += substr_count($row['micro_analysis'], ",") + 1;
  }

  echo $end_result;
Sign up to request clarification or add additional context in comments.

Comments

1

Replace your code with the following:

$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";

      $count_query = mysqli_query($conn, $sql);
      $count_fetch = mysqli_fetch_assoc($count_query);
      $end_result=0;//initialize variable to 0
      foreach ($count_fetch as $k => $row) {
         if($k == 'micro_analysis'){
           $result = substr_count($row, ",") + 1; //change over here
           $end_result += $result;
         }
      }

      echo $end_result;

6 Comments

I get an error ` Illegal string offset 'micro_analysis'`
before foreach
add the following code: echo "<pre>"; print_r($count_fetch);die();
Array ( [sample_id] => 16 [env_sam_id] => 181207-9-1 [order_id] => 21 [c_sam_id] => Test [sample_group] => water [sample_type] => Test [sample_condition] => Test [sample_temp] => Test [storage_location] => 1 [s_status] => Analysis Pending [s_time1] => 17:36:11 [s_date1] => 2018-12-07 [micro_analysis] => 1,2,3 [chem_analysis] => 1,2 )
For some reason it provides the incorrect answer. The answer that @Nigel Ren gave worked for me. Thank you anyways!
|

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.