dtlygweb2017 2014-06-11 19:34
浏览 27
已采纳

如果没有发布值,则将NULL插入SQL数据库[duplicate]

This question already has an answer here:

I know there are many questions in this subject, but I just can't understand. I'm making an insert into a database with a post with php. Whenever my fields are empty it is inserting a '0' in the database instead of a NULL value... My code is as follows:

<?php
$host=""; // Host name 
$username=""; // Mysql username 
$contra=""; // Mysql password 
$db_name=""; // Database name 

// Connect to server and select database.
$dbh= mysql_connect("$host", "$username", "$contra")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form 
$var1=$_POST["var1"]; 
$var2=$_POST["var2"]; 
$var3=$_POST["var3"]; 
$var4=$_POST["var4"]; 

// To protect MySQL injection
$var1=stripslashes($var1);
$var2=stripslashes($var2);
$var3=stripslashes($var3);
$var4=stripslashes($var4);

$var1 = mysql_real_escape_string($var1);
$var2 = mysql_real_escape_string($var2);
$var3 = mysql_real_escape_string($var3);
$var4 = mysql_real_escape_string($var4);

            $sql="INSERT INTO PREGUNTAS (Var1, Var2, Var3, Var4) VALUES('$var1', '$var2', '$var3', '$var4');";
            $table= mysql_query($sql, $dbh) or die ("you've got a problem");            
                    }
    break;
}
 ?>

I tried starting the variable like this

$var2 = isset($_POST["var2"]) ? "'$var2'" : "NULL";

and

if($_POST['var2'] == "") $_POST['var2'] = "NULL";

but none of them worked, the query is still adding 0's.

and I am getting the following error/notice:

Notice: Undefined index: var2 in /.....php on line ...

Could you please help me?

Thanks!

</div>
  • 写回答

3条回答 默认 最新

  • dragon4587 2014-06-11 19:38
    关注

    You've quoted your field values in the query, so even if you set a particular variable to be the string NULL in PHP, you'd still be trying to do

    INSERT ... VALUES ('NULL', ...)
    

    An SQL NULL is a keyword, It cannot be quoted if you want the DB to treat it as an actual null value, e.g.

    INSERT ... VALUES(NULL, 'NULL', ...)
                      ^^^^---actual SQL null
                            ^^^^^^--- a string which contains the letters N, U, L, L
    

    That means you need to rebuild your query differently:

    if ($_POST['var1'] == '') {
        $db_var1 = 'NULL';
    } else {
        $db_var1 = "'" . mysql_real_escape_string($_POST['var1']) . "'";
    }
    
    INSERT ... VALUES($db_var1, ...)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line