<?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>
主键是employees
表中的email
,我知道这不是一种安全的方法,我应该使用准备语句,但这只是一个小项目。 'dayoff' 有一个自动递增的 int 'id' 作为主键。
所以发生的情况是所有记录都被插入多次。并且一些记录fname
和lname
被连接并存储在dayoff
表
fname
中
最佳答案
您有语法错误
INSERT INTO dayoff (fname,lname,datef) VALUES ($_POST[select1]).$_POST[select1] will contains fnamelname.
此外,您没有获得日期
值即:$_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>
关于php - 选择框多次插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34120017/