tags:

views:

139

answers:

2

This is a continuation of the discussion at

http://stackoverflow.com/questions/944158/php-multiple-dropdown-box-form-submit-to-mysql

which ended with the words: "Once you have the variables, it is trivial to create new rows." No doubt that's generally true, but apparently not for this learner... :-D

Given the following form:

    <form action="form.php" method="POST">
    <select name="colors[]" multiple="yes" size="2">
    <option>Red</option>
    <option>Blue</option>
    </select>
    <input type="submit" value="Go!"> 
    </form>

how do I create new rows? The following script

foreach($_POST['colors[]'] as $color) 
    {
        $id = mysqli_real_escape_string($link, $color);
        $sql = "INSERT INTO colors SET id = '$id'";
    }

raises the error

 Warning: Invalid argument supplied for foreach() in form.php on line ...

whereas the following

    $colors = $_POST['colors[]']; 
    for ($i = 0; $i < count($colors); $i++) 
        {
            $color = $colors[$i];
            $sql = "INSERT INTO colors SET id = '$color'";
        }

raises no errors but does no row creation.

What triviality am I missing here?

+2  A: 

Use:

foreach($_POST['colors'] as $color) 

No need to specify [] here, php knows that it is an array.

Sarfraz
Thanks! That got rid of the error.
PeterC
@PeterC: it is good news than and thank you
Sarfraz
Yes, however I'm still not getting the database to create rows. I created a table like so: CREATE TABLE colors (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,color TEXT); --- I can't see what the problem is...
PeterC
@Peterc: I could not understand your comment completely but why don't you use a sql client software such as sqlyog to create your table?
Sarfraz
@Sarfraz - good suggestion. I think I found the problem. Thanks again for your help!
PeterC
What was the problem? It helps for others who encounter the problem to know where you found the problem and an alternative solution for it.
Anthony Forloney
@Peterc: You are welcomed :)
Sarfraz
@Anthony - it was precisely what you said in your answer below - I had left out the mysql_query statement. Doh! :-D
PeterC
+1  A: 

Inside of your foreach loop I did not see that you are executing the query. You need to execute mysql_query with your INSERT statement.

foreach($_POST['colors'] as $color) {
 $id = mysqli_real_escape_string($link, $color);
 $sql = "INSERT INTO colors SET id = '$id'";
  if (!mysql_query($sql)) {  // if the query encountered a problem.
     die('Invalid query: ' . mysql_error());
  } 
}
Anthony Forloney
@Anthony - That's correct - as I just discovered (to my chagrin)! Thanks for the help.
PeterC
bene, buona fortuna!
Anthony Forloney