[英]Php inserts data into database with empty values before form is submitted?
I'm trying to use this code from this site which inserts empty fields into a database when the page is initially loaded and when the form's fields are filled out and submitted, then another batch of data is inserted into the database (MySQL). 我正在尝试使用此站点中的代码,该站点在初始加载页面时将空字段插入到数据库中,并且在填写并提交表单的字段时,将另一批数据插入到数据库(MySQL)中。 How this behavior can be avoided?
如何避免这种行为?
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
<?php
if($_POST['submit']){
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
}
?>
You have to check if($_POST['submit']) variable has a value set. 您必须检查($ _ POST ['submit'])变量是否设置了值。
also you need to add some value and a name to your input type="submit" html element 你还需要在input type =“submit”html元素中添加一些值和名称
<input type="submit" name="submit" value="Submit!" />
You need to check for isset()
of your submit button before inserting otherwise it will insert an empty row at each load, so add it 在插入之前,您需要检查提交按钮的
isset()
否则会在每次加载时插入一个空行,因此请添加它
</body>
</html>
<?php
if(isset($_POST['submit']))
{
$con=mysqli_connect("example.com","peter","abc123","my_db");
//all your code here
}
Note that your submit button is missing name so change it to 请注意,您的提交按钮缺少名称,因此请将其更改为
<input type"submit" name="submit">
Put your insert code jn an if statement like: 将插入代码jn放在if语句中:
If (isset($_post)) { Code here } 如果(isset($ _ post)){Code here}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.