简体   繁体   English

使用PHP进行表单和SQL验证

[英]Form and SQL Validation using PHP

When user clicks on the Save, check whether the data is successfully inserted record to the table, and display a proper message accordingly. 当用户单击“保存”时,检查是否已成功将数据插入记录表中,并相应地显示适当的消息。 If forms are empty then the error message should be shown and database should not have any record. 如果表单为空,则应显示错误消息,并且数据库不应有任何记录。

//SAVE

if (isset($_POST['SAVE'])) {
    $Name = $_POST['name'];
    $City = $_POST['city'];
    $query = "Insert Into Info Values('$Name','$City')";
    $result = mysqli_query($con, $query) or die ("query is failed" . mysqli_error($con));
    $Name = '';
    $City = '';
    if(mysqli_affected_rows($con)>0) {
        echo "record is saved";
    }else {
        echo "record is not saved";
    }

I can only do validation through php. 我只能通过php进行验证。 I am not sure if I am doing this right. 我不确定我是否这样做正确。 So far I can get the "record is saved" message on my form, but I cannot get the latter if the form are empty. 到目前为止,我可以在表单上获取“保存记录”消息,但是如果表单为空,则无法获取后者。 It just make an empty record in my database. 它只是在我的数据库中做一个空记录。

Checking isset($_POST['SAVE']) only tells you if "SAVE" is set. 检查isset($_POST['SAVE'])仅告诉您是否设置了“ SAVE”。 It does not tell you if the fields have values. 它不会告诉您这些字段是否具有值。

To do the validation in PHP, use something like the following: 要在PHP中进行验证,请使用类似以下内容的代码:

if (isset($_POST['SAVE'])) {
    $Name = $_POST['name'];
    $City = $_POST['city'];
    if ($Name && $City)
    {
       //...
       //code to insert data into the database goes here
       //...

       if(mysqli_affected_rows($con)>0) {
          echo "record is saved";
       }else {
          echo "record is not saved (error saving)";
       }
    } else {
       echo "record is not saved (input was empty)";
    }
}

The key being the if ($Name && $City) check. 关键是if ($Name && $City)检查。

Alternately, if you want to rely on mysql to reject the insert on blank values, then make sure the fields in the mySql table are not nullable and then change this part of your code: (but this would be moving the validation to MySql) 或者,如果您想依靠mysql拒绝对空白值的插入,请确保mySql表中的字段不可为空,然后更改代码的这一部分:(但这会将验证移至MySql)

$Name = $_POST['name']?$_POST['name']:null;
$City = $_POST['city']?$_POST['city']:null;

Untested Code: 未经测试的代码:

if (!isset($_POST['SAVE'], $_POST['name'], $_POST['city'])) {  // avoid Notices
    echo "Missing required submission data";
} elseif (!strlen(trim($_POST['name']))) {  // validate however you wish
    echo "Name data is not valid";  // explain however you wish
} elseif (!strlen(trim($_POST['city']))) {  // validate however you wish
    echo "City data is not valid";  // explain however you wish
} elseif (!$con = new mysqli("localhost", "root", "", "db")) {  // declare and check for a falsey value
    echo "Connection Failure"; // $con->connect_error <-- never show actual error details to public
} elseif (!$stmt = $con->prepare("INSERT INTO Info VALUES (?,?)")) {
    echo "Error @ prepare"; // $con->error;  // don't show to public
} elseif (!$stmt->bind_param("ss", $_POST['name'], $_POST['city'])) {
    echo "Error @ bind";  // $stmt->error;  // don't show to public
} elseif (!$stmt->execute()) {
    echo "Error @ execute";  // $stmt->error;  // don't show to public
} else {
    echo "Insert Successful"; 
}

The validation conditions on the submission data ensure that the values are not empty and they are not completely comprised of whitespace characters. 提交数据上的验证条件可确保这些值不为空,并且不完全由空格字符组成。 If you wish to refine the validation requirement further, just update the conditions. 如果您希望进一步完善验证要求,只需更新条件即可。

If you want to simply ensure that $_POST['name'] and $_POST['city'] are not empty, you can replace the first three conditionals with 如果只想确保$_POST['name']$_POST['city']不为空,则可以将前三个条件替换为

if (empty($_POST['SAVE']) || empty($_POST['name']) || empty($_POST['city'])) {
    echo "Submission data is missing/invalid";
}...

If you don't use a prepared statement, then name values like Paul O'Malley will break your query. 如果您不使用准备好的语句,那么Paul O'Malley类的名称值将破坏您的查询。 Worse, if someone wants to try to run some injection attacks, your query is vulnerable. 更糟糕的是,如果有人想尝试进行一些注入攻击,则您的查询很容易受到攻击。

Checking affected_rows() is unnecessary. 不需要检查affected_rows() If there is no error message from the query execution, the INSERT query was a success. 如果查询执行没有错误消息,则INSERT查询成功。

The above suggestions are all best practices which I urge you to adopt. 以上建议是我敦促您采用的所有最佳做法。

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

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