将NULL附加到字符串,用于MySQL插入查询

时间:2017-03-09 14:53:22

标签: php mysql

我正在尝试向MySQL数据库添加一个新条目,最后5个参数是可选的,因此可以使用NULL值。根据收到的POST数据,我在查询字符串中附加NULL值时遇到问题
如何将NULL值附加到查询字符串?

//more similar mysqli_real_escape_string rows and if clauses above these lines
$phonenumber=mysqli_real_escape_string($db,$_POST["phonenumber"]);
$gender = NULL;
if($_POST["gender"] != null)
   $gender=(int)mysqli_real_escape_string($db,$_POST["gender"]);
$age = NULL;
if($_POST["age"] != null)
   $age = (int)mysqli_real_escape_string($db,$_POST["age"]);
$qs_registration="insert into uporabnik (ID, up_ime, geslo, email, ime, priimek, naslov_bivanja, posta_foreign_key,
tel_stevilka, spol, starost) VALUES (NULL, '".$username."','".$password."','".$email."','".$name."',
'".$surname."','".$location."',".$postoffice.",'".$phonenumber."',".$gender.",".$age.")";

2 个答案:

答案 0 :(得分:0)

如果你需要一个空值,例如:在一列中使用和auto_increment id ..那么你可以省略相关的值(你可以避免字符串连接,因为&#39; $ yourvar&#39;就足够了)< / p>

    "insert into uporabnik (up_ime, geslo, email, ime, priimek, 
      naslov_bivanja, posta_foreign_key, tel_stevilka, spol, starost)
    VALUES ('$username','$password','$email','$name',
         '$surname','$location', $postoffice','$phonenumber',$gender,$age.")";

无论如何要小心传递var你应该eval一个paramaetrized查询而不是传递var以避免sqlinjection

答案 1 :(得分:0)

首先,您应该使用准备好的陈述 - When should I use prepared statements?

但是,如果您只是寻找答案,只需将初始变量设置为字符串'NULL'

这样,当您连接所有内容时,您将获得MySQL可以理解的查询字符串:

$age = 'NULL';
if($_POST["age"] != null) {
    // Wrap each variable in quotes
   $age = "'" . (int)mysqli_real_escape_string($db,$_POST["age"]) . "'";
}
// etc.

$qs_registration="insert into uporabnik (ID, up_ime, geslo, email, ime, priimek, naslov_bivanja, posta_foreign_key,
tel_stevilka, spol, starost) VALUES (NULL, " . $username . "," . $password . "," . $email . "," . $name . ",
" . $surname . "," . $location . "," . $postoffice . "," . $phonenumber . "," . $gender . "," . $age . ")";

注意:我认为这里存在很多其他问题,从不使用预准备语句(如前所述)到如何首先配置表。但这应该可以解决你手头的问题。