selectbox多次插入值

时间:2015-12-06 16:48:31

标签: php mysql

<?php
require '../common/connect-db.php';
require_once 'admin-template.php';
?>
<form id="form1" name="form1" method="post" action="test.php">
<?php
 // add button
if(isset($_POST['add_dayoff'])) {
$AddQuery = "INSERT INTO dayoff (fname,lname,datef)
VALUES ('$_POST[select1]')";
mysqli_query($db,$AddQuery);
};
?>
<?php
$query="SELECT DISTINCT fname, lname FROM employees";
$result = $db->query($query);
?>
<table><caption>Dayoff Table</caption>
     <tr>
     <th>First Name</th>
     <th>Employee Dayoff</th>
     </tr>
     <tr>
<td><select name="select1" id="select1" >
<?php
echo '<option value="">Please select...</option>';
while ($row = mysqli_fetch_array($result)) {
    echo "<option value='" . $row['fname'] . $row['lname'] . "'>" . $row['fname'] ." ". $row['lname'] . "</option>";
}
?>

<td><input type="date"  name="date" required /></td>
</select></td>
<td><input type="submit"  name="add_dayoff" /></td>

</tr>
</table>

e email表中的主键是mployees,我知道这不是一种安全的方法,我应该使用prepare语句,但它只是一个小项目。 'dayoff'有一个自动递增的int'id'作为主键。

所以会发生的是所有记录都被多次插入。一些记录fnamelname被连接起来并存储在fname表格dayoff

1 个答案:

答案 0 :(得分:2)

您有语法错误

INSERT INTO dayoff (fname,lname,datef) VALUES ($_POST[select1]).$_POST[select1] will contains fnamelname.

此外,您没有获得dateie:$_post['date'].试试这个,让我知道结果

  <?php
    require_once 'admin-template.php';
    ?>
    <form id="form1" name="form1" method="post" action="test.php">
    <?php
    // add button
    if(isset($_POST['add_dayoff'])) {
    $fname=$_POST['select1'];// get the value which stores firstname-lastname
    $n=explode('-',$fname);//explode the value with -
    $datef=$_POST['date'];
    $AddQuery = "INSERT INTO dayoff (fname,lname,datef) VALUES ('$n[0]','$n[1]',$datef)";// query should be like this 
    mysqli_query($db,$AddQuery);
    };
    ?>
    <?php
    $query="SELECT DISTINCT fname, lname FROM employees";
    $result = $db->query($query);
    ?>
    <table><caption>Dayoff Table</caption>
    <tr>
    <th>First Name</th>
    <th>Employee Dayoff</th>
    </tr>
    <tr>
    <td><select name="select1" id="select1" >
    <?php
    echo '<option value="">Please select...</option>';
    while ($row = mysqli_fetch_array($result)) {
    echo "<option value='". $row['fname']."-".$row['lname'] . "'>" . $row['fname'] ." ". $row['lname'] . "</option>";
    }
    ?>
    <td><input type="date"  name="date" required /></td>
    </select></td>
   <td><input type="submit"  name="add_dayoff" /></td>
   </tr>
    </table>