J. 4RK
J. 4RK

Reputation: 62

UPDATE an imploded multiple selection into database

I have a problem while updating a to database, It happens to add the new value beside the old value into the database for example

Upvotes: 0

Views: 1825

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

There are few issues with your code, such as:

  • $tags is not an array. See the below statement in your while() loop,

    $tags = $row['tags'];
    

    So you can't use it in foreach loop like that. Use explode() function to split the string and get the tags in an array, like this:

    $tags = explode(",",$row['tags']);
    

    And then use this $tags array in your form, which is explained below.

  • Syntax error here,

    $tags = implode(",",$_POST['tags'];
                                      ^ missing closing )
    
  • Even you get the tags as an array(as pointed above), you don't have to use that foreach loop either, it will unnecessarily append additional/redundant tags in your <select> element. better use in_array() function to check the tag value is present in $tags array or not and make it selected accordingly

  • value attribute is missing from <option> tags.

  • Place the SELECT operation below the UPDATE operation, otherwise you'll get old tag values from the SELECT operation even if you update the tags using the form.

So your code should be like this:

if(isset($_POST['update'])){
    $tags = implode(",",$_POST['tags']);
    $query = "UPDATE data SET tags= '$tags' WHERE id = $id";
    mysqli_query($dbc, $query);
}

$query = "SELECT * FROM data WHERE id = $id";
$edit = mysqli_query($dbc, $query);
while($row = mysqli_fetch_assoc($edit)){
    $tags = explode(",",$row['tags']);
}

<form method="post" action="index.php">
    <select id="tags" name="tags[]" multiple="multiple">
        <option value="tag1"<?php if(in_array('tag1', $tags)){ echo ' selected="selected"'; } ?>>tag1</option>
        <option value="tag2"<?php if(in_array('tag2', $tags)){ echo ' selected="selected"'; } ?>>tag2</option>
        <option value="tag3"<?php if(in_array('tag3', $tags)){ echo ' selected="selected"'; } ?>>tag3</option>
        <option value="tag4"<?php if(in_array('tag4', $tags)){ echo ' selected="selected"'; } ?>>tag4</option>
    </select>
    <button type="submit" name="update">Submit</button>
</form>

Upvotes: 2

Related Questions