这是表tbl_temp:
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->name赋null但这里赋的值是0这会导致重复的错误如果赋null,那就没问题了因为mysql的唯一值是空的,但不能是零
首先,将您的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();
你不必改变你的表,如果你不想,我只是建议这样做,但基本上,如果你想设置null,只需使用bindValue(':name', null, PDO::PARAM_STR);
试试这个
$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')
如果$field变量为空(''
),它将返回NULL,否则$field
你可以像CASE WHEN '$field'='' THEN NULL ELSE '$field' END
或者甚至
$stmt->bindValue(':name', $this->name?:null, PDO::PARAM_NULL);
(注意上面的例子没有转义,也不安全,只是一个使用的例子)