Insert data into mysql database from multiple select lists (html form)

I am making a form where there is a store identifier:

<input type="text" name="shopId">

and there is a choice of several options:

<select name="cars" multiple required>

after I get the selected parameters, I have to transfer them to a table in the database; The table consists of two columns: shopId and car. The fact is that it skips only one option, and it is impossible to add several rows to the table, as in one store, two or three models. I suppose I have to pass data as an array or something like that. Can you help me please.

$shopId = $_GET["shopId"];
$cars = $_GET["cars"];

this is a request:

$query = "INSERT INTO shops (shopId, car) VALUES ($shopId, $cars)";
+3
source share
2 answers

, , , , , ( PHP, implode http://php.net/implode), shopID , , . :

<?php
    if ($_POST) {
        $cars_string = implode(', ', $_POST['cars']);
        $sql = '
            INSERT INTO
                `my_table` (
                    `shopID`,
                    `cars`
                )
            VALUES (
                '. $_POST['shopID'] .',
                "'. $cars_string .'"
            )
        ';
        mysql_query($sql) OR die(mysql_error());
    }
?>

<form method="post" action="">
Shop ID: <input type="text" name="shopID"/> - 
<select name="cars[]" multiple="multiple">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="honda">Honda</option>
    <option value="audi">Audi</option>
    <option value="bmw">BMW</option>
</select>
<input type="submit" name="Submit"/>
</form>

, . , , submit. , .

, <select> name="cars[]" / cars[]. , . , , @bart2puck . , - multiple="multiple" <select>.

+10

1 , $_GET ['cars'] . , , []. , $_GET .

, .

 $shopId = $_GET['shopId'];
 foreach ($_GET['cars'] as $value) 
 {
  $ins = "INSERT INSERT INTO shops (shopId, car) VALUES ($shopId, $value)";
 }

1 , , - :

  $cars = "";
 foreach ($_GET['cars'] as $value)
 {
        $cars .= $value . ",";
 }
 $cars = substr($cars,0,-1);  //to remove the last comma

 $ins = "INSERT INSERT INTO shops (shopId, car) VALUES ($shopId, $cars)";

"honda, mazda, toyota", .

-1

All Articles