如何使用Select2插件添加从数据库下拉列表中选择的多个值

时间:2014-06-13 13:26:56

标签: php jquery-select2

我需要的是什么:

  • 当用户从下拉列表中选择多个值时必须将所有值插入数据库中。

我的问题:

  • 仅插入一个值。

    以下是我的代码的快照:http://postimg.org/image/h3on9ti6r/

    这是我的示例代码:

    if(isset($_POST['submit']))
    {
      $team=$_POST['team'];
      $teamname=$_POST['teamname'];
      $query="INSERT INTO teamname(People_Name, Team_Name) VALUES   ('".$team."','".$teamname."')" ;
      $rs=mysql_query($query);
      $num=mysql_num_rows($query);
    
    }
    

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>

我已经尝试了我的更新代码但是问题:只插入了一个字段

   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++;
 }   
}

1 个答案:

答案 0 :(得分:1)

team将是$_POST中的数组。您必须迭代其元素以将所有值插入数据库。

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

您不应使用已弃用的mysql_*个函数,请使用mysqli_*版本的isntead或PDO。我推荐后者。它更安全。您可以找到更多信息here