简体   繁体   English

PHP/mySQL INSERT NULL 如果变量为空

[英]PHP/mySQL INSERT NULL if variable is empty

i want to check if a variable from $_POST is empty and INSERT a NULL to my Database.我想检查$_POST的变量是否为空并将 NULL 插入到我的数据库中。

But when I do it my way i always get a String called NULL and not a real NULL in my data set.但是当我按照自己的方式进行操作时,我总是在我的数据集中得到一个名为 NULL 的字符串,而不是真正的 NULL。
This is how I tried it:这是我尝试的方式:

if(isset($_POST['folge'])){
    $comment = !empty($_POST['comment']) ? "'".$_POST['comment']."'" : null;

    $sqlstring = "INSERT INTO eventstest (comment) VALUES (".$comment.")";
    echo $sqlstring;
    if ($mysqli->query($sqlstring) === TRUE) {
      printf("Table myCity successfully created.\n");
    }else{
      printf("Errorcode: %d\n", $mysqli->errno);
        printf("Error: %d\n", $mysqli->error);
    }

if I send the form without making inputs to "comment" page output is:如果我发送表单而不输入“评论”页面输出是:

INSERT INTO eventstest (comment) VALUES ()Errorcode: 1136 Error: 0 INSERT INTO eventstest (comment) VALUES ()Errorcode: 1136 Error: 0

Whats wrong?怎么了? Or whats the better way to check for empty inputs and add NULL to DB?或者检查空输入并将NULL添加到数据库的更好方法是什么?

PS: The database cell has STANDARD: NULL PS:数据库单元格有 STANDARD: NULL

If you want to insert a NULL value into MySQL, you have to pass a null-value in the SQL query, not the string of null.如果你想在 MySQL 中插入一个NULL值,你必须在 SQL 查询中传递一个空值,而不是空字符串。 It will still be a string from a PHP perspective, but not from the MySQL perspective.从 PHP 的角度来看,它仍然是一个字符串,但从 MySQL 的角度来看则不是。

if (!empty($_POST['comment'])) {
    $comment = "'".$mysqli->real_escape_string($_POST['comment'])."'";
} else {
    $comment = "NULL";
}

You can also shorten that into a one-liner, using a ternary operator您还可以使用三元运算符将其缩短为单行

$comment = !empty($_POST['comment']) ? "'".$mysqli->real_escape_string($_POST['comment'])."'" : "NULL";

Then, because you assign the quotes around the comment-string itself, as you should do, since you alternatively want to pass a null-value, you need to remove the single quotes surrounding the variable from the query.然后,因为您在注释字符串本身周围分配了引号,正如您应该做的那样,因为您或者想要传递一个空值,所以您需要从查询中删除围绕变量的单引号。 This would otherwise break it too, as you'd get ''comment'' .否则这也会破坏它,因为你会得到''comment''

$sql = "INSERT INTO table (comment) VALUES (".$comment.")";

Of course this assumes that the column comment allows for null-values.当然,这假设列comment允许空值。 Otherwise it will fail, in which case you should either insert empty strings or change the column to accept null values.否则它将失败,在这种情况下,您应该插入空字符串或更改列以接受空值。


It should also be noted that this query is exposed to SQL injection attacks, and you should use an API that supports prepared statements - such as PDO or MySQLi, and utilize those to secure your database against these kinds of attacks.还应该注意的是,此查询会受到 SQL 注入攻击,您应该使用支持预准备语句的 API - 例如 PDO 或 MySQLi,并利用它们来保护您的数据库免受此类攻击。 Using a prepared statement with MySQLi would look something like this.在 MySQLi 中使用准备好的语句看起来像这样。 See how we supply a PHP null to the value in bind_param() if $_POST['comment'] is empty.看看如果$_POST['comment']为空,我们如何为bind_param()的值提供一个 PHP null值。

// Set MySQLi to throw exceptions on errors, thereby removing the need to individually check every query
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

if (isset($_POST['folge'])) {
    // $comment = !empty($_POST['comment']) ? $_POST['comment'] : null; // Ternary operator
    $comment = $_POST['comment'] ?? null; // Null coalescing operator, since PHP 7

    $sql = "INSERT INTO eventstest (comment) VALUES (?)";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("s", $comment);
    $stmt->execute();
    $stmt->close();
}

Several things wrong here.这里有几件事不对。 First is that you are using string concatenation instead of prepared statements.首先是您使用的是字符串连接而不是准备好的语句。 This leaves you open to SQL injection.这让您对 SQL 注入持开放态度。 I suggest you stop this project right now and return after learning to use PDO and prepared statements.我建议你现在停止这个项目,在学习使用 PDO 和准备好的语句后回来。

Secondly, 'NULL' != null you need to specify it as null其次, 'NULL' != null您需要将其指定为null

Last but not least, generally there isn't a need to explicitly check for null in postvars and then pass a null again.最后但并非最不重要的一点是,通常不需要显式检查 postvars 中的 null,然后再次传递 null。 If the column type allows null and you do not pass in a non null value.如果列类型允许 null 并且您没有传入非 null 值。 null will be stored in it anyway null 无论如何都会存储在其中

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

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