PHP,PDO,如何插入NULL到MySQL当输入为其他空白的输入值

问题描述:

这是表tbl_temp:PHP,PDO,如何插入NULL到MySQL当输入为其他空白的输入值

id(pri unique)  name(unique, null able) 
1     abc 
2     null 
3     eadf 
4     null 
5     null 

这是插入功能:

$stmt = $this->conn->prepare("INSERT INTO tbl_temp (id, name) values (:id, :name); 
$stmt->bindParam(':id', $this->id, PDO::PARAM_INT); 
$stmt->bindParam(':name', $this->name); 
$stmt->execute(); 

这是对于插入功能

<from action='' method='post'> 
     <input type='text' name='name'> 
     <input type='submit' /> 
</form> 

现在这里的视图如果值是空白输入名字,就应该空分配给bindParam->的名字,但它” S^0分配在这里被赋予重复的错误,如果它给null,则这将是确定的值,因为MySQL可以有独特的空但不为零

+0

-1,为什么?你能解释一下吗? – SAR

+0

这是一个不真实的代码。它包含语法错误。 2.它不包含将名称变量赋值为0的代码。 –

+0

检查字段是否为空否则插入值或插入空 – Diamond

首先,设置你的id列自动增加,第二,改变你的说法

"INSERT INTO tbl_temp (name) values (:name);" 

如果你不使用id,为什么不自动增加它?

最后,使用这样的:

$stmt = $this->conn->prepare("INSERT INTO tbl_temp (name) values (:name);") 
$name = $this->name; 
if($name == ""){ 
    $stmt->bindValue(':name', null, PDO::PARAM_STR); 
} else{ 
    $stmt->bindParam(':name', $this->name, PDO::PARAM_STR); 
} 


$stmt->execute(); 

你没有改变你的表,如果你不想,我只是建议这样做,但基本上如果你想设置为空,只需使用bindValue(':name', null, PDO::PARAM_STR);

+0

这个自动增量与问题有什么关系? –

+0

我同意迪玛。在问题中,id列是:'id(pri unique)'。似乎没有理由不自动增量。 – misterManSam

+0

@misterManSam如果它只是来自其他表的外键呢?无论哪种方式,与这个关于名称字段的问题有什么关系? –

试试这个

$name = $this->name; 
if(empty($name)){ 
    $name = null; 
} 
$stmt = $this->conn->prepare("INSERT INTO tbl_temp (id, name) values (:id, :name)"); 
$stmt->bindParam(':id', $this->id, PDO::PARAM_INT); 
$stmt->bindParam(':name', $name); 
$stmt->execute; 

MySQL(5.6+)具有函数NULLIF(a,b)其中,如果a = b,则返回NULL,否则返回a

INSERT INTO table (a,b,c) VALUES (123,NULLIF('$field',''),'xyz') 

如果$场变量是空的(''),它会返回NULL,否则$场

你可以做手工像CASE WHEN '$field'='' THEN NULL ELSE '$field' END甚至

$stmt->bindValue(':name', $this->name?:null, PDO::PARAM_NULL); 

(注意上面的例子没有逃脱,不安全,但只是一个例子)