user3703097
user3703097

Reputation: 139

How to Add Multiple values Selected from Dropdown in Database Using Select2 Plugin

What I Need:

MY problem :

HTML code:

<form id="contactForm" action="" method="post">
<fieldset>                      
    <p>
        <label for="name" >Team</label>
          <input type="hidden" id="123">
       <select multiple id="e2" name="team[]" style="width:300px">
    <?php
    $query= mysql_query("select Distinct Name from users ");
    while($result=mysql_fetch_assoc($query)){
    ?>
       <option value=" <?php echo $result['Name']?> "><?php echo $result['Name']?></option>
       <?php
    }
    ?>
    </select>

    </p>


    <p>
       <label for="Team Name">Enter the Team Name</label>
        <textarea  name="teamname"  id="teamname" type="text" rows="5" cols="20" class="form-poshytip" title="Enter the Team Name"></textarea>
    </p>



    <!-- ENDS send mail configuration -->

    <p><input type="submit" value="Send" name="submit" id="submit" /> <span id="error" class="warning">Message</span></p>
</fieldset>

i have tried my updated code but prob: only one filed are inserted

   if(isset($_POST['submit']))
 {
$team=$_POST['team'];
  $teamname=$_POST['teamname'];
  $ct = 0; 
  foreach ($team as $value)
     {
  echo $value;
  echo $query="INSERT INTO teamname(People_Name) VALUES ('".$value."')" ;
  $rs=mysql_query($query);
  $num=mysql_num_rows($query);
  serialize($team);
  $ct++;
 }
  $c = 0; 
  foreach ($teamname as $value1)
     {
  echo $value1;
  echo $query1="INSERT INTO teamname(Team_Name) VALUES ('".$value1."')" ;
  $rs1=mysql_query($query1);
  $num=mysql_num_rows($query1);
  serialize($teamname);
  $c++;
 }   
}

Upvotes: 0

Views: 2771

Answers (1)

dtengeri
dtengeri

Reputation: 937

The team will be an array in your $_POST. You have to iterate over its elements to insert all of the values into your database.

if(isset($_POST['submit']))
{
  $team=$_POST['team'];
  // Do not trust the data that is submitted by the user. 
  // Prevent yourself from SQL injection.
  $teamname=mysql_real_escape_string($_POST['teamname']);
  foreach ($team as $t) {
    $query="INSERT INTO teamname(People_Name, Team_Name) VALUES   ('".$t."','".$teamname."')" ;
    $rs=mysql_query($query);
    $num=mysql_num_rows($query);
  }
}

You should not use mysql_* functions they are deprecated, use the mysqli_* versions isntead or PDO. I recommend the latter one. It is much safer. You can find more information here.

Upvotes: 2

Related Questions