0

I have participants form with multiple select option:

<select name="userid[]" id="" multiple>
    <option value="1">xyz</option>
    <option value="2">xy1</option>
    <option value="3">1aw</option>
    <option value="4">abc</option>
</select>

I selected 3 users and saved to database with $participents = implode(',', $_POST['userid']); and database saved as 1,2,3.

Now I want to remove a user from participant list by clicking remove button.

$pid = $_POST['pid']; //participant form id
$id = $_POST['id'];   // user id i need to delete

$aa = mysqli_query($conn, "SELECT * from `participant_registrations` where id='$pid' ")  or
    die(mysqli_error($conn));

$bb = mysqli_fetch_assoc($aa);
$ss = implode(',', array($bb['participents']));
unset($ss[array_search($id, $ss)]);
mysqli_query($conn, "UPDATE `participant_registrations` SET participents='$ss' WHERE id='$pid' ")  or die(mysqli_error($conn));

But I'm getting error like:

Warning: array_search() expects parameter 2 to be array, string given in C:\wamp64\www\bkjy\participantlist.php on line 17

Fatal error: Uncaught Error: Cannot unset string offsets in C:\wamp64\www\bkjy\participantlist.php on line 17

Help me where it went wrong.

Community
  • 1
  • 1
G Karthik
  • 7
  • 2

1 Answers1

1

You have to use explode() to split the string into an array. And then you have to use implode() to put it back into the table.

$ss = explode(',', $bb['participents']);
$index = array_search($id, $ss);
if ($index !== false) {
    array_splice($ss, $index, 1);
    $participents = implode(',', $ss);
    $stmt = mysqli_prepare($conn, "UPDATE `participant_registrations` SET participents=? WHERE id=? ");
    mysqli_stmt_bind_param($stmt, "ss", $participents, $pid);
    mysqli_stmt_execute($stmt);
}

You should also use prepared statements instead of substituting variables into SQL, I've shown that change above.

Barmar
  • 741,623
  • 53
  • 500
  • 612