php - 如何通过 FORM 将数据插入 MYSQL
问题描述
在过去的两天里,我一直在尝试创建一个表单来将数据输入到 SQL 数据库中。数据库功能正常,表格已制作,我可以通过 MYSQL 输入数据。我正在使用 2 个文件,bidinput.html
并且bidentry.php
出价输入.HTML:
<html>
<body>
<form action="bidentry.php" method="post">
Bidder: <input type="text" name="BidderNumber"><br>
Description: <input type="text" name="Description"><br>
Price: <input type="decimal" name="Price"><br>
Quantity: <input type="integer" name="Quantity"><br>
Lot: <input type="text" name="Lot"><br>
<input type ="submit">
</form>
</body>
</html>
bidentry.php:
<?php
######### From bidinput.html
$BidderNumber = $_POST['BidderNumber'];
$Description = $_POST['Description'];
$Price = $_POST['Price'];
$Quantity = $_POST['Quantity'];
$Lot = $_POST['Lot'];
########
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "abcd1234";
$dbname = "auction";
// Create connection
$mysqli = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
// Check connection
if ($mysqli->connect_errno){
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}
else{
echo "Connected successfully";
$sql = "INSERT INTO Bids (BidderNumber,Description,Price,Quantity,Lot) VALUES ('$BidderNumber','$Description','$Price','$Quantity','$Lot')";
echo "Error: " . $sql . "<br>" . $mysqli->error;
}$mysqli->close();
?>
当我运行单击提交按钮时,我收到以下错误:
连接成功错误:INSERT INTO Bids (BidderNumber,Description,Price,Quantity,Lot) VALUES ('202','candy','3','1','')
解决方案
警告您需要保护自己免受 SQL 注入。您应该使用准备好的语句来保护自己免受 SQL 注入的影响。
您实际上并没有使用当前代码运行任何查询。
您需要使用mysqli 查询:
$mysqli->query($sql);
准备好的语句示例
这是一个基于您的代码的带有准备好的语句的 INSERT 示例:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
$stmt = $mysqli->prepare("INSERT INTO Bids (BidderNumber, Description, Price, Quantity, Lot) VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss", $_POST['BidderNumber'], $_POST['Description'], $_POST['Price'], $_POST['Quantity'], $_POST['Lot']);
$stmt->execute();
$stmt->close();
编辑:把它放在你的 PHP 文件的顶部:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
您不想在生产中显示错误,但在开发环境中没关系。您可能需要检查您的 PHP.INI 文件。至少log_errors
应该默认打开,并且错误将记录在您的 apache 错误日志中。
推荐阅读
- aws-sam-cli - 从 Python 脚本中运行 AWS SAM 构建
- oracle - 如何使用oracle sql将货币金额检索为单词
- regex - 如何从字符串中间删除空格但在开头保留空格?
- mysql - 添加外键时mysql中的死锁
- javascript - 使用VPN时可以使用jquery CDN吗?- 使用 TamperMonkey
- php - 如何在 PHP 中拆分时间值?
- java - Kafka Listener 无法消费消息并坚持到 hbase 表
- java - 如何在 Spring Boot 2.1.4 版本中使用 Maven Build 从文件名中删除版本号?
- dax - DAX 在不存在时也会计算先前的值
- xaml - Xamarin TapGestureRecognizer 有时无法正常工作