0

I have these data in my booked_tickets table:

1st Row: A1, A3, B2

2nd Row: C3, D2, A2

3rd Row: C1, A2, D1

When I tried to concatenate these data into one string, I get this: A1, A3, B2C3, D2, A2C1, A2, D1

What I wanted is: A1, A3, B2, C3, D2, A2, C1, A2, D1

How do I concatenate like that?

if (mysqli_num_rows($resultData) > 0){
    while ($row = mysqli_fetch_assoc($resultData)) {
        $updateBookedSeats = $updateBookedSeats.$row['selected_bus_seats'];
        $updateTotalPassengers = $updateTotalPassengers + $row['number_of_passengers'];
    }
    mysqli_stmt_close($stmt);

    $updateBookedSeats = explode(",", $updateBookedSeats);
    sort($updateBookedSeats);
    $updateBookedSeats = implode(",", $updateBookedSeats);
}

Ignore the $updateTotalPassengers, that works fine on its own.

3
  • This $updateTotalPassengers = $updateTotalPassengers + can be simplified to $updateTotalPassengers += you then should put a , in there. You can use rtrim after the loop to remove the last one... or $updateBookedSeats is the same thing... and use .= for the operator. Commented Jun 14, 2021 at 15:04
  • I just managed to solve it similar like your solution. I concatenate a comma and then got rid of the last comma character by using a substr(). Thanks for the help! Commented Jun 14, 2021 at 15:28
  • rtrim will be safer than substr because it would only remove a trailing comma. Commented Jun 14, 2021 at 16:41

1 Answer 1

1

I think you need to update this line

$updateBookedSeats = $updateBookedSeats.$row['selected_bus_seats'];

With additional , at end like:

$updateBookedSeats = $updateBookedSeats.$row['selected_bus_seats'].',';

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

2 Comments

This works!. I'll then just use a substr() function to get rid of the last comma character. Thanks for the help!
To get rid of the last comma character you could use rtrim($s,',') instead of substr().

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.