php - 将选项从 html 选择框发送到数据库
问题描述
更新:我现在收到一条错误消息,告诉我 roomID 为空,这就是它没有进入数据库的原因。当它应该是用户在选择框中选择的选项时,你能明白为什么它会为空吗?
我正在研究酒店预订系统作为练习。我正在尝试制作一个将新预订插入数据库的表格。我在 mySQL 数据库中有客户和房间 IDS,并将它们放入 HTML 选择框中,供用户选择一个选项。
这工作正常,直到我尝试将新预订保存到数据库中。我没有收到任何错误,它告诉我预订已保存在我的页面上,但如果我进入数据库,它还没有保存。我尝试从文本框中插入 customerID 和 roomID 值,所以只需输入它而不是下拉菜单,然后插入数据库就好了。
我很确定问题与将值从选择框中取出并放入 POST 变量有关,但我不是 100% 确定。我只写了 6 个月的代码,所以我真的不知道我在做什么!我试图通过查看此处的其他示例来解决这个问题,但似乎没有任何效果。
这是我的代码:
获取数据以填充选择框:
//Locate room names
$query = $query = 'SELECT `roomID` FROM `room`';
$result2 = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result2);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result2);}
//Locate customerIDs
$query = $query = 'SELECT `customerID` FROM `customer`';
$result = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result);}
创建选择框:
<form method="POST" action="newbooking.php">
<p>
<label for="customerID">Customer ID: </label>
<?php
echo "<select name='customerID'id='customerID' input type='number'>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='customerIDselect'>" . $row['customerID'] . "</option>";
//customerID
$customerID = cleanInput($_POST['customerIDselect']);
}
echo "</select>";
?>
</p>
<p>
<label for="rooms">Room (name, type, beds): </label>
<?php
echo "<select name='roomID'id='roomID' input type='number'>";
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "<option value='roomIDselect'>" . $row['roomID'] . "</option>";
//roomID
$roomID = cleanInput($_POST['roomIDselect']);
}
echo "</select>";
?>
</p>
将数据插入数据库:
//save the customer data if the error flag is still clear
if ($error == 0) {
$query = 'INSERT INTO `bookings` (`customerID`,`roomID`,`checkin`,`checkout`, `extras`) VALUES (?,?,?,?,?)';
$stmt = mysqli_prepare($DBC,$query); //prepare the query
mysqli_stmt_bind_param($stmt,'sssss', $customerID, $roomID, $checkin, $checkout, $extras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>booking saved</h2>";
} else {
echo "<h2>$msg</h2>".PHP_EOL;
}
解决方案
推荐阅读
- c++ - 创建一个超类的指针数组以堆分配继承的类
- discourse - 由于违反内容安全政策,discourse 电子邮件激活不再有效
- mysql - SQL 结果长度,搜索时不显示任何内容
- r - Lattice panel.abline 在数据点后面绘制线
- python - 如何构建一个函数来基于包含某个字符串的其他列创建一个新列?
- php - PHP 致命错误:尝试运行测试示例时找不到类“WP_UnitTestCase”
- c# - 从控制台应用程序使用 RestSharp 时收到的空白值
- ios - React Native iOS Build in Release 配置冻结在启动屏幕上
- python-3.x - GnuPG 已安装,但 python 在运行时找不到它
- java - sonarqube 中的包命名问题