我正在使用此代码将数据发送到mysql数据库,其功能也很好,尽管用户也在发送空白数据并进行复制。

<?php
  require "conn.php";
  $lostidno = $_POST ["lostidno"];
  $phonenol = $_POST ["phonenol"];

  $mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";

  if ($conn->query($mysql_qry) === TRUE)
  {
    echo "Information Recieved!";
  }
  else
    echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;

  $conn->close();

?>


我该如何预防?

最佳答案

您可以使用trim函数删除字符串开头和结尾的空格。之后,您可以检查两个参数是否不为空:

<?php
require "conn.php";
$lostidno = trim($_POST["lostidno"]);
$phonenol = trim($_POST["phonenol"]);

if(!empty($lostidno) && !empty($phonenol))
{
    $mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";

    if ($conn->query($mysql_qry) === TRUE) {
        echo "Information Recieved!";
    }
    else {
        echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;
    }

    $conn->close();
}
?>


您还应该查看this以防止SQL injections

10-08 09:33