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

时间:2014-02-24 00:56:50

标签: php html mysql forms

我正在尝试使用此代码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);
?> 

3 个答案:

答案 0 :(得分:4)

<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'])变量是否设置了值。

您还需要为输入类型=“提交”html元素

添加一些值和名称
<input type="submit" name="submit" value="Submit!" />

答案 1 :(得分:2)

在插入之前需要检查提交按钮的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">

答案 2 :(得分:1)

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

if(isset($ _ post)){     代码在这里 }