繁体   English   中英

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

[英]Php inserts data into database with empty values before form is submitted?

我正在尝试使用此站点中的代码,该站点在初始加载页面时将空字段插入到数据库中,并且在填写并提交表单的字段时,将另一批数据插入到数据库(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);
}
?> 

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

你还需要在input type =“submit”html元素中添加一些值和名称

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

在插入之前,您需要检查提交按钮的isset()否则会在每次加载时插入一个空行,因此请添加它

</body>
</html> 
<?php

if(isset($_POST['submit']))
{
     $con=mysqli_connect("example.com","peter","abc123","my_db");

     //all your code here
}

请注意,您的提交按钮缺少名称,因此请将其更改为

<input type"submit" name="submit">

将插入代码jn放在if语句中:

如果(isset($ _ post)){Code here}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM