我在PHP中创建了一个简单的表单,因此我可以将提交的数据添加到数据库中。连接工作正常,但每次刷新表单页面时,它都会在数据库中添加一个空行。此外,它还显示错误消息“未定义的索引:第38行的C:\ xampp \ htdocs \ projekt \ submitform.php中的Fname ”
这是我到目前为止编写的代码:
<?php include 'config.php'; ?>
<?php
$Fname = isset($_POST['Fname'])?$_POST['Fname']:'';
$Lname = isset($_POST['Lname'])?$_POST['Lname']:'';
$Email = isset($_POST['Email'])?$_POST['Email']:'';
$PhoneNo = isset($_POST['PhoneNo'])?$_POST['PhoneNo']:'';
$query = "INSERT INTO users(Fname,Lname,Email,PhoneNo) VALUES ('$Fname','$Lname','$Email','$PhoneNo')";
$result = mysqli_query($con,$query) or die ("problem inserting data into database");
?>
<p><span class="error">* required field</span></p>
<form action = "" method = "post">
Name: <input type = "text" name = "Fname">
<span class=error>*</span><br>
Surname: <input type="text" name="Lname">
<span class=error>*</span><br>
Email: <input type = "email" name = "Email">
<span class=error>*</span><br>
Phone Number: <input type = "tel" name="PhoneNo"><br>
<input type = "submit" value="submit">
</form>
答案 0 :(得分:1)
你需要检查是否有像这样的POST变量:
if (isset($_POST['Fname'])) { //here you can check whatever post values you want to check
$Fname = $_POST['Fname'];
$Lname = $_POST['Lname'];
$Email = $_POST['Email'];
$PhoneNo = $_POST['PhoneNo'];
$query = "INSERT INTO users(Fname,Lname,Email,PhoneNo) VALUES
('$Fname','$Lname','$Email','$PhoneNo')";
$result = mysqli_query($con,$query) or die ("problem inserting data into
database");
}
因为每次访问页面时都会尝试插入记录,但只有在有值的情况下才需要插入记录(意味着有人填写表格)
因此您需要检查刷新是否来自表单提交
答案 1 :(得分:1)
您应该'监听'发布请求,然后才能插入值。
<?php
if(isset($_POST['submit'])) {
$Fname = $_POST['Fname'];
$Lname = $_POST['Lname'];
$Email = $_POST['Email'];
$PhoneNo = $_POST['PhoneNo'];
$query = "INSERT INTO users(Fname,Lname,Email,PhoneNo) VALUES ('$Fname','$Lname','$Email','$PhoneNo')";
$result = mysqli_query($con,$query) or die ("problem inserting data into database");
}
?>
你得到的错误告诉你没有发布数据集。
请注意,直接使用SQL的输入数据存在巨大的安全风险!在存储输入数据时,您至少应该使用mysqli
和mysqli_real_escape_string($Fname)
。
更安全的是使用PDO and prepared statement。