3

I have a group chat feature on my site and people can add friends by selecting HTML checkboxes, so multiple can be added at one point. However, when my PHP script inserts the data into the MySQL database, only the last value is added. For example, if the user selects 3 friends, PHP separates their ID's by commas (as it will be stored as an array in the database); so it would display like ,1,2,3. However, when I insert into MySQL, only the ",3" is submitting.

PHP code to assemble data from HTML checkbox:

$invite = $_POST['invite'];
  if(empty($invite)) 
  {
    //echo("You didn't select any friends.");
  } 
  else
  {
    $N = count($invite);

    //echo("You selected $N friends(s): ");
    for($i=0; $i < $N; $i++)
    {
      $userinput = ("," . $invite[$i]);
    }
  }

MySQL query:

$sql = "INSERT INTO group_chat (title, created_date, last_modified, created_by, user_array) VALUES ('$title', now(), now(), '$logOptions_id', '$logOptions_id$userinput')";

$logOptions_id contains the ID of the current user.

I've echoed the $userinput variable out before and it appears as it should be: ,1,2,3 (comma at the start seperates from current user ID when adding to MySQL.

2 Answers 2

5

You are overwriting the values in the loop with this line

$userinput = ("," . $invite[$i]);

Change it to this

$userinput .= ("," . $invite[$i]);

Remember to initialize the the variable $userinput before appending to it to avoid undefined variable warning.

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

2 Comments

Thanks, that's the answer. :)
@AmalMurali I will accept the answer but StackOverFlow is saying I can accept it in 2 mins
0

you can create the comma separated id string using implode

$userinput = implode(',', $invite); // output as 1,2,3

If you want to add current user id to it

$userinput = $logOptions_id.','.implode(',', $invite);

1 Comment

@Chibuzo an alternate option to create comma separated string from array

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.