gpt4 book ai didi

Php 在提交表单之前将数据插入具有空值的数据库?

转载 作者:可可西里 更新时间:2023-11-01 07:52:35 25 4
gpt4 key购买 nike

我正在尝试使用此代码 from this site它在页面最初加载时将空字段插入数据库,当表单的字段填写并提交时,另一批数据被插入数据库(MySQL)。如何避免这种行为?

<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);
}
?>

您必须检查 if($_POST['submit']) 变量是否设置了值。

您还需要为您的 input type="submit"html 元素添加一些值和名称

<input type="submit" name="submit" value="Submit!" />

关于Php 在提交表单之前将数据插入具有空值的数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21976996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com