2

This is a continuation of the discussion at

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 Answers 2

2

Use:

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

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

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

5 Comments

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: 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 - good suggestion. I think I found the problem. Thanks again for your help!
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 - it was precisely what you said in your answer below - I had left out the mysql_query statement. Doh! :-D
1

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());
  } 
}

1 Comment

@Anthony - That's correct - as I just discovered (to my chagrin)! Thanks for the help.

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.