Ayla
Ayla

Reputation: 114

Select box options to write to new row in database - MySQL and PHP

I have a form which currently has the following fields:

Name, Size, Template

There are two select boxes in this form for the fields 'Size' and 'Template'. I want the form to insert a new row if a user selects more than one option on the select box.

I have managed to do this for 'Template' but I can not figure out how to use the foreach construct twice so that it also inserts a new row when multiple options are selected from the Size field.

Here is my code which works for inserting a new row for multiple 'Template' selected options:

$template = $_POST['Template'];
$size = $_POST['Size'];

foreach( $template as $temp ) {

  switch( $temp ) {
 case '1':
   $template;
 break;
 case '2':
   $template;
 break;
 case '3':
   $template;
 break;
  case '4':
   $template;
 break;
 };

 $query = "INSERT INTO tbl (Name,Size,Template) VALUES('$name', '$size', '$temp')";
 }

Is there a way to use this foreach statement twice but to run the same query.

For example, I was thinking to do

foreach( $size as $newsize) {
switch( $newsize ) {

//cases go here

};
}

Upvotes: 1

Views: 100

Answers (1)

dimlucas
dimlucas

Reputation: 5141

The for loop would be more appropriate for what you've been trying to achieve:

for($i=0; $i<count($size); $i++)
{
    for($j=0; $j<count($template); $j++)
    {
        $currentSize = $template[$i];
        $currentTemplate = $template[$j];
        $query = "INSERT INTO tbl (Name, Size, Template) VALUES('$name', '$currentSize', '$currentTemplate')";
    }
}

Warning: I only wrote the query in the same way you did to demonstrate the rest of the code. The query is actually vulnerable to SQL Injection attacks and you should definitely avoid it. Instead write the query like this:

$query = "INSERT INTO tbl (Name, Size, Template) VALUES(?,?,?)";

The question marks are place holders. You will need to prepare this statement and then bind $name, $currentTemplate and $currentSize to them before executing. Check this for more information on prepared statements. Since you need to execute the same query multiple times with different data you have one more reason to use prepared statements. I highly recommend you check Example#3 of the documentation in the link above

Upvotes: 1

Related Questions