How do I leave NULL if $_POST is empty in the Mysql database?

Asked

Viewed 361 times

1

Is there any way I can leave it as null fields that have not been filled in? When creating the table, fields have already been defined as DEFAULT NULL, but while doing the Insert - in the database Mysql - for $_POST, the fields which have not been filled in remain empty.

Below this the code.

if (isset($_POST['update'])) {

    $nome          = $_POST['nome'];
    $sobrenome     = $_POST['sobrenome'];
    $nivel         = $_POST['nivel'];
    $date     = date('Y-m-d H:i:s');

    $_SESSION['warning']['type']    = "success"; // tipos success, info, warning e error
    $_SESSION['warning']['message'] = "Player Created Successfully!"; // mensagem que vai aparecer

    if (empty($_POST['nome'])) {
        $_SESSION['warning']['type']    = "error"; // tipos success, info, warning e error
        $_SESSION['warning']['message'] = "The NAME is required."; // mensagem que vai aparecer
        echo "history.go(-1);";
        exit;
    }

    $vsl = "INSERT INTO `files` (`id`, `nome`, `sobrenome`, `nivel`, `date`)VALUES(NULL, '$nome', '$sobrenome', '$nivel', '$date')";
    $rsl = mysqli_query($conn, $vsl);

    header("Location: add.php");
    exit();

}

1 answer

0


As this inserting via PHP simple quotes is different from null an idea is to put in variable the contents example:

$sobrenome = strlen($sobrenome) > 0 ? "'$sobrenome'" : "NULL";
$vsl = "INSERT INTO files (id, nome, sobrenome, nivel, date) VALUES(NULL, '$nome', $sobrenome, '$nivel', '$date')";
$rsl = mysqli_query($conn, $vsl);

That would solve.

  • I did the example only in the $surname field but can be done at all.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.