Search code examples
phpmysqlnull

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


Solution

  • 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 would look something like this. See how we assign a PHP null to $comment variable when $_POST['comment'] is not set.

    if (isset($_POST['folge'])) {
        $comment = $_POST['comment'] ?? null;
        $sql = "INSERT INTO eventstest (comment) VALUES (?)";
        $stmt = $conn->prepare($sql)->execute([$comment]);
    }