-2

I want to add multiple Country name in one row.

I am using Select Option Multiple country Name but I want to submit selected Country Name in a row after comma like (USA, UK, CA, etc..)

If I use for each loop then this code submits record every country name in different rows.

<select name="Country[]" multiple>
   <option value="USA">United State of America</option>
   <option value="UK">United Kingdom</option>
   <option value="CA">Canada</option>
</select>
<?php
if(isset($_POST['Submit'])){
   foreach ($_POST['Country'] as $i){
       $sql = "INSERT INTO Country (id, countries) VALUES ('', '$i')";
       $con->query($sql) === TRUE;
   }
}
?>

If i am using this code then this code submit only one country name.

if(isset($_POST['Submit'])){
   foreach ($_POST['Country'] as $i){
       $countryname = $i;
   }
   $sql = "INSERT INTO Country (id,countries) VALUES ('', '$countryname')";
   $con->query($sql) === TRUE;
}
catcon
  • 1,295
  • 1
  • 9
  • 18
Imran Hafeez
  • 62
  • 10

1 Answers1

2

You just need to convert all the country names into a comma separated list (using implode) before the INSERT:

if(isset($_POST['Submit'])){
    $sql = "INSERT INTO Country (id,countries) VALUES ('', '" . implode(',', $_POST['Country']) . ")";
    $con->query($sql);
}

Note that you should use a prepared statement to avoid the possibility of SQL injection (for example, for MySQLi):

if(isset($_POST['Submit'])){
    $sql = "INSERT INTO Country (id,countries) VALUES ('', ?)";
    $stmt = $con->prepare($sql);
    $countries = implode(',', $_POST['Country']);
    $stmt->bind_param('s', $countries);
    $stmt->execute();
}

Also, in general, storing data in a table in comma separated lists is a bad idea. See this Q&A.

Nick
  • 138,499
  • 22
  • 57
  • 95