刷新页面时,停止INSERT INTO创建新行

时间:2014-09-15 04:31:57

标签: php mysql database insert-into

我在下面有这个代码,它工作正常,除非我刷新页面时插入一个空行。有谁知道我需要做什么?

<?php
$con=mysqli_connect("localhost","name","password","inventory");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$inv_number = mysqli_real_escape_string($con, $_POST['inv_number']);
$date = mysqli_real_escape_string($con, $_POST['date']);
$date_type = mysqli_real_escape_string($con, $_POST['date_type']);
$item1 = mysqli_real_escape_string($con, $_POST['item1']);
$location1 = mysqli_real_escape_string($con, $_POST['location1']);

$sql="INSERT INTO invoice (inv_number, date, date_type, item1, location1)
VALUES ('$inv_number', '$date', '$date_type', '$item1', '$location1')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}
echo 'Invoice #'.$_POST['inv_number'].' recorded'; 

mysqli_close($con);
?>

我尝试查找条件if语句,这些语句可以防止代码创建空白行,但无法找到工作解决方案。

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

<?php
$con=mysqli_connect("localhost","name","password","inventory");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (empty($_POST['inv_number']) || empty($_POST['date']) ||empty($_POST['date_type'])
    || empty($_POST['item1']) || empty($_POST['location1'])) 
    {
      echo "Re direct user by using header or show them messages";

    }
else {
    // set your variable and run your query 
    //i just copy and posted your code from your question
// escape variables for security
$inv_number = mysqli_real_escape_string($con, $_POST['inv_number']);
$date = mysqli_real_escape_string($con, $_POST['date']);
$date_type = mysqli_real_escape_string($con, $_POST['date_type']);
$item1 = mysqli_real_escape_string($con, $_POST['item1']);
$location1 = mysqli_real_escape_string($con, $_POST['location1']);

$sql="INSERT INTO invoice (inv_number, date, date_type, item1, location1)
VALUES ('$inv_number', '$date', '$date_type', '$item1', '$location1')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}
echo 'Invoice #'.$_POST['inv_number'].' recorded'; 
}
mysqli_close($con);
?>

重要的是要注意,如果if语句中给出的任何feild为空,则查询将不会运行

请阅读解决方案中的评论