Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

后端 未结 5 1205
Happy的楠姐
Happy的楠姐 2020-12-29 19:42

The following is a snippet from my HTML form which pulls the options from the table rows accordingly.

What I want to do is have the first option value to be NULL so

相关标签:
5条回答
  • 2020-12-29 19:51

    Yes, it is possible. You have to do something like this:

    if(isset($_POST['submit']))
    {
      $type_id = ($_POST['type_id'] == '' ? "null" : "'".$_POST['type_id']."'");
      $sql = "INSERT INTO `table` (`type_id`) VALUES (".$type_id.")";
    }
    

    It checks if the $_POST['type_id'] variable has an empty value. If yes, it assign NULL as a string to it. If not, it assign the value with ' to it for the SQL notation

    0 讨论(0)
  • 2020-12-29 19:55

    In php 7 you can do:

    $_POST['value'] ?? null;
    

    If value is equal to '' as said in other answers it will also send you null.

    0 讨论(0)
  • 2020-12-29 20:04

    that's why Idon't like NULL values in the database at all.
    I hope you are having it for a reason.

    if ($_POST['location_id'] === '') {
      $location_id = 'NULL';
    } else {
      $location_id = "'".$_POST['location_id']."'";
    }
    $notes = mysql_real_escape_string($_POST['notes']);
    $ipid  = mysql_real_escape_string($_POST['ipid']);
    
    $sql="UPDATE addresses 
        SET notes='$notes', location_id=$location_id
        WHERE ipid = '$ipid'";
    
    echo $sql; //to see different queries this code produces
    // and difference between NULL and 'NULL' in the query
    
    0 讨论(0)
  • 2020-12-29 20:12

    No, POST/GET values are never null. The best they can be is an empty string, which you can convert to null/'NULL'.

    if ($_POST['value'] === '') {
        $_POST['value'] = null; // or 'NULL' for SQL
    }
    
    0 讨论(0)
  • All you need is a check on the post side of things.

    if(empty($_REQUEST['type_id']) && $_REQUEST['type_id'] != 0)
        $_REQUEST['type_id'] = null;
    
    0 讨论(0)
提交回复
热议问题