简体   繁体   中英

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.

But when I do it my way i always get a String called NULL and not a real NULL in my data set.
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

Whats wrong? Or whats the better way to check for empty inputs and add NULL to DB?

PS: The database cell has 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. It will still be a string from a PHP perspective, but not from the MySQL perspective.

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'' .

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

Of course this assumes that the column comment allows for null-values. 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. Using a prepared statement with MySQLi would look something like this. See how we supply a PHP null to the value in bind_param() if $_POST['comment'] is empty.

// 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. I suggest you stop this project right now and return after learning to use PDO and prepared statements.

Secondly, 'NULL' != null you need to specify it as null

Last but not least, generally there isn't a need to explicitly check for null in postvars and then pass a null again. If the column type allows null and you do not pass in a non null value. null will be stored in it anyway

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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