A little bit of everything…
RSS icon Home icon
  • Saving multiple selections from drop down list to database

    Posted on March 20th, 2009 Aleix 1 comment

    phpThis post will teach you how to process and store multiple selections from a form element into a MySQL database, using PHP. In order to understand how it works, you will need basic knowledge of PHP arrays, because they’re necessary for achieving the results.

    If you still don’t know what arrays are and how do they work, read Tizag’s array tutorial first.

    In the example we will use five options in a multiple selection drop down list. The form is in index.php; when the form is submitted the selected options will be sent to formsubmit.php, where they will be processed as appropriate and saved to the database.

    This is a demo of how it works.

    And this is the code you need:


    index.php

    
    <html>
    <head>
    <title>Page title</title>
    </head>
    <body>
    <p>Options:</p>
    <form method="POST" action="formsubmit.php">
    <p>
    <select size="5" name="options[]" multiple="multiple">
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
    <option>Option 4</option>
    <option>Option 5</option>
    </select></p>
    <p><input type="submit" value="Send" name="Send"></p>
    </form>
    </body>
    </html>
    

    As you can see it is a pretty simple form. The magic here is done by the name of the drop down list: as you can see, the name is options[]. The brackets in the end make PHP automatically place the selected options into an array. The same trick can be used with checkboxes too, because multiple selections can be made as well.

    If you would now try to save the submitted data to the database, you would find out all what is saved is ‘array’. Here is where serialize() function comes to the rescue!


    formsubmit.php

    
    <?php
    $options = $_POST['options'];  // Retrieve POST data
    if(isset($options)){  // Check if selections were made
    
    // Serialize
    
    $serializedoptions = serialize($options);
    
    // Save to the database
    
    $con = mysql_connect('localhost','admin','password123');
    mysql_select_db('dbname', $con);
    $sql="INSERT INTO tablename (options) VALUES ('$serializedoptions')";
    mysql_query($sql) or die(mysql_error());
    
    // Show confirmation
    
    echo 'The following options were saved to database:<br /><br />';
    
    foreach($options as $key => $value){
    echo $value . "<br />";
    }
    
    } else {  // User selected nothing
    
    echo 'No options selected!';
    
    }
    ?>
    

    I will explain what exactly does the code above do. First of all it retrieves the POST variables, so that we can use them in the processing stage and save them to the database. Then, with the help of isset(), it checks whether the options variable is set or not: if the user made no selections, then the variable is not set and it’s pointless to query the database, so it skips the process and echoes immediately a message saying that no options were selected.

    array

    Without using serialize()

    If isset() returns true, then it means some options were selected and therefore we want to save them to the database. But before running the code which connects to and queries the database, there’s a very important step to be taken: serialize.

    Click here to see an interactive demo of how serialize() works.

    Serialize() generates a storable representation of an array. If we would not serialize the array we want to save, all what would appear in the database would be ‘array’.  But by serializing, the array will be stored properly and in a way which is human readable. It is important to note, that when you want to retrieve a serialized array, you will have to unserialize it. As you can imagine, the unserialize() function does exactly the opposite from what serialize() does. Neat, eh?

    With serialize()

    Using serialize()

    Finally, the code makes the query to insert the data into the chosen table. A confirmation is then shown to the user, displaying the selections he made; to do that the foreach() loop is used. The loop will retrieve all the contents of the array and echo them.

    You can see again the demo in action here, and the serialize() demo here.

    That’s it, for now :)

     

    Related posts:


     

    One response to “Saving multiple selections from drop down list to database”

    1. Hello Alex,

      Thanks for the quick run down on how you store multiple selection.

      I think this is a dilema that mySql has not properly addressed. The way you proposed is fine, however the values you store into the database cannot be properly related to quries for retrieving the data.

      This is why I see it as a dilema because serialized storage cannot help in database searches :(

    Leave a reply