简体   繁体   English

表单验证。 $ _POST如果不是null可能吗?

[英]Form validation. Is $_POST if NOT null possible?

Is it possible to tell php to NOT post data if the form field is null? 如果表单字段为空,是否可以告诉php不要发布数据?

right now my post variables in my insert.php page look like this: 现在,我在insert.php页面中的post变量如下所示:

fname = $_POST['firstname'];
lname = $_post['lasname'];

sql = "UPDATE profile SET first='.$fname.', last='.$lname.' WHERE id='.$id.'";

If my form fields are empty or null, I'd like the $fname $lname not to post. 如果我的表单字段为空或为空,我希望不发送$ fname $ lname。 What would be the best method to do this? 最好的方法是什么?

Currently when i submit an update, if those fields are empty they update the entire table with empty rows if nothing is inserted. 目前,当我提交更新时,如果这些字段为空,那么如果没有插入任何内容,它们将使用空行更新整个表。

You could use something like this for each field: 您可以在每个字段中使用类似的内容:

$fname = empty($_POST['firstname']) ? null : $_POST['firstname'];

This will set $fname to null if the form field does not exist or the input was empty. 如果表单字段不存在或输入为空,这会将$fname设置$fname null。 Otherwise, it will use the original value. 否则,它将使用原始值。

Update 更新资料

If you want to only update fields that aren't null, you'll need to add some extra logic: 如果只想更新不为null的字段,则需要添加一些额外的逻辑:

if($fname !== null && $lname !== null) {
    // update both
}
else if($fname !== null) {
    // update just fname
}
else if($lname !== null) {
    // update just lname
}

Is it possible to tell php to NOT post data if the form field is null? It isn't PHP who is posting data, it is your browser the moment you hit the submit button of the form. 发布数据的不是PHP,而是单击表单的Submit按钮后的浏览器。 In order to prevent this from happening when the fields are empty, you will have to use something client-sided (javascript), which first validates if the fields are indeed filled in before the form is submitted. 为了防止在字段为空时发生这种情况,您将必须使用客户端(javascript),它首先会在提交表单之前验证字段是否确实已填写。

This is how I understand your question though. 这就是我对您的问题的理解。 If you don't want to create the SQL query when the $_POST variables are empty, then simply use an if condition or a ternary operator. 如果不想在$_POST变量为空时创建SQL查询,则只需使用if条件或三元运算符。

I'd do this: 我会这样做:

$fname = isset($_POST['firstname']) && strlen($_POST['firstname']) > 0 ? $_POST['firstname'] : null;

This way, $fname will be defined to the $_POST['firstname'] value if the variable is set and not empty, otherwise it will be null 这样,如果设置了变量并且不为空,则将$ fname定义为$ _POST ['firstname']值,否则它将为null

By the way, if you're working inside double quotes ( " ), there's no need to use a dot to add values to the $sql string. Even more, your syntax is wrong. This is a working way to do it: 顺便说一句,如果您在双引号( " )中工作,则无需使用点将值添加到$ sql字符串中。甚至,您的语法是错误的。这是一种可行的工作方式:

$sql = "UPDATE profile SET first='$fname', last='$lname' WHERE id='$id'";

You should NOT use this kind of SQL-query generation. 应该使用这种SQL查询生成。 It's vulnerable to SQL injections. 它容易受到SQL注入的攻击。 Better use PDO or MySQLi parametrized queries. 更好地使用PDOMySQLi参数化查询。

And, by the way, if you want to deny the insertion if a value is empty, you better do it when creating the MySQL table (assigning a not null property to the column). 而且,顺便说一句,如果您想在值为空的情况下拒绝插入,则最好在创建MySQL表(将not null属性分配给该列)时执行。 For example: 例如:

CREATE TABLE user(
    first VARCHAR(50) NOT NULL,
    last VARCHAR(50) NOT NULL
)

** EDIT: If I'm understanding well, this is that you want: **编辑:如果我理解得很好,这是你想要的:

$valuesToAdd = "";
// Concatenate values to the query if they are defined
if (isset($_POST['firstname']) && strlen($_POST['firstname']) > 0) $valuesToAdd .= "first = '{$_POST['firstname']}',";
if (isset($_POST['lastname']) && strlen($_POST['lastname']) > 0) $valuesToAdd .= "last = '{$_POST['lastname']}',";
// Repeat for any other values...

// By default, the SQL string is empty
$sql = "";

// If changes were made...
if (strlen($valuesToAdd) > 0) {
    // Remove the last ","
    $valuesToAdd = substr($valuesToAdd, 0, strlen($valuesToAdd)-1);

    // Generate the SQL string with the values which will be added
    $sql = "UPDATE profile SET {$valuesToAdd} WHERE id='{$id}'";

    // echo $sql; die;
}


// Check if the SQL string is not empty
if (strlen($sql) > 0) {
    // Here the SQL has been generated, use it for a SQL query...
    // $con = mysql_connect(...); .....
}
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];

$sets = array();

if(trim($fname)) {
  $sets[] = "first = '".mysql_real_escape_string($fname)."'";
}
if(trim($lname)) {
  $sets[] = "last = '".mysql_real_escape_string($lname)."'";
}

if($sets) {
  $sql = "UPDATE profile SET ".implode(", ", $sets)." WHERE id='".mysql_real_escape_string($id)."'";
}

Remember to properly escape your values before you glue them to SQL. 在将值粘贴到SQL之前,请记住正确地转义您的值。

You need form validation. 您需要表单验证。 Easy solution will not allow empty fields save in db and prevent SQL-injections . 简单的解决方案不允许将空字段保存在db中,并防止SQL注入

Easy solution : 简单的解决方案

$fname = isset($_POST['firstname']) and nameIsValid($_POST['firstname'])
    ? $_POST['firstname'] : false;
$lname = isset($_POST['lastname']) and nameIsValid($_POST['lastname'])
    ? $_POST['lastname'] : false;

if (false === $fname or false === $lname) {
    // report about not valid form fields
} else {
    $dsn = 'mysql:dbname=yourdb;host=yourhost;charset=utf8';
    $dbh = new PDO($dsn, 'user', 'pass');
    $sql = "UPDATE profile SET first = :fname, last = :lname WHERE id = :id";

    $stmt = $dbh->prepare($sql);
    $stmt->execute(array(':fname' => $value, ':lname' => $lname, ':id' => $id));
}

/**
 * Validation names for empty values
 *
 * @param string $name First name or last name
 * @return bool
 */
function nameIsValid($name) {
    return '' !== $name;
}

But be aware of XSS-injection . 但是要注意XSS-injection For example somebody can save in your db Fist name: 例如,有人可以在您的db Fist名称中保存:

<script>alert('Woohoo! You have vulnerability!');</script>

And next time, when you print First name of the user, everyone will see message about vulnerability :) 下次,当您打印用户的名字时,每个人都会看到有关漏洞的消息:)

You may decide implement more strict validation rules, which will not allow names like "asfyua23807*^2#" , "-2*&%$9837239askHF" or XSS-injections. 您可以决定实施更严格的验证规则,不允许使用诸如“ asfyua23807 * ^ 2#”“-2 *&%$ 9837239askHF”或XSS-injections的名称。 In this case you should modify nameIsValid() function. 在这种情况下,您应该修改nameIsValid()函数。

Safe solution: 安全解决方案:

/**
 * Validation names and prevent XSS-injections
 *
 * @param string $name First name or last name
 * @return bool
 */
function nameIsValid($name) {
    $pattern = '/^[\.a-z-]+$/i';
    return (bool) preg_match($pattern, $name);
}

This logic allow names containing Az . 此逻辑允许名称包含Az。 - symbols: J.Jameson , Jackson-Piterson , JOHn , smIth , etc . -符号:J.Jameson, 杰克逊Piterson, 约翰· 史密斯 For more strict validation rules check Official PHP Regular Expressions manual . 有关更严格的验证规则,请查看PHP正则表达式官方手册

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

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