如果没有$ _POST值

时间:2016-04-14 15:09:25

标签: php mysql mysqli

我尝试了多种尝试方法来实现这一目标。已经尝试过以前关于这个主题的所有回答方式而无法得到它。

如果$ _POST变量没有值,我试图将 NULL 而不是字符串NULL插入数据库。它只是不断插入字符串' NULL'或者只是一个空白栏目。以下是我尝试查询的所有方法。

我的数据库类有一个方法sql_prep

public function sql_prep($postVariable){
  $output;
  if(trim($postVariable) == ''){
    $output = 'NULL';
  }else{
  $output = strval(mysqli_real_escape_string($this->connection, $postVariable));
  };
  return $output;
}

以下是查询:

 if(isset($_POST["createUserSubmit"])) : 
  $temp_connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
  $firstName = $db->sql_prep($_POST["firstName"]);
  $lastName = $db->sql_prep($_POST["lastName"]);
  $companyName = $db->sql_prep($_POST["companyName"]);
  $streetAddress = $db->sql_prep($_POST["streetAddress"]);
  $streetAddress2 = $db->sql_prep($_POST["streetAddress2"]);
  $streetAddress3 = $db->sql_prep($_POST["streetAddress3"]);
  $city = $db->sql_prep($_POST["city"]);
  $state = $db->sql_prep($_POST["state"]);
  $zip = $db->sql_prep($_POST["zipCode"]);
  $country = $db->sql_prep($_POST["country"]);
  $phone = $db->sql_prep($_POST["phone"]);
  $fax = $db->sql_prep($_POST["fax"]);
  $email = $db->sql_prep($_POST["email"]);
  mysqli_query($temp_connection, "INSERT INTO Address(firstName, lastName, companyName, address1, address2, address3, city, state, zip, country, phone, fax, email, dateCreated, dateModified) VALUES (" . $firstName . ", " . $lastName . ", " . $companyName . ", " . $streetAddress . ", " . $streetAddress2 . ", " . $streetAddress3 . ", " . $city . ", " . $state . ", " . $zip . ", " . $country . ", " . $phone . ", " . $fax . ", " . $email . ", NOW(), NOW())");
  mysqli_close($temp_connection);
  redirect_to('./create-user.php');
endif;

即使填写了该字段,该查询也不会将任何数据推送到数据库。我尝试查询的另一种方式:

mysqli_query($temp_connection, "INSERT INTO Address(firstName, lastName, companyName, address1, address2, address3, city, state, zip, country, phone, fax, email, dateCreated, dateModified) VALUES ('{$firstName}', '{$lastName}', '{$companyName}', '{$streetAddress}', '{$streetAddress2}', '{$streetAddress3}', '{$city}', '{$state}', '{$zip}', '{$country}', '{$phone}', '{$fax}', '{$email}', NOW(), NOW())");

这将返回字符串' NULL'如果$ _POST变量为空,则进入数据库。我还尝试将sql_prep函数更改为:

public function sql_prep($postVariable){
  $output;
  if(trim($postVariable) == ''){
    $output = NULL; //returned PhP Null instead of string 'NULL'
  }else{
  $output = strval(mysqli_real_escape_string($this->connection, $postVariable));
  };
  return $output;
}

更改它以返回PhP NULL而不是' NULL'导致查询只将空白列推入数据库。

无法解决这个问题,如果没有值,我真的想推送SQL NULL。

1 个答案:

答案 0 :(得分:2)

尝试使用prepared statements,这有助于您保持安全。

$var = NULL;
$stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)");
$stmt->bind_param("s", $var);
$stmt->execute();

应为您插入NULL值。