PDO bindValue在Codeigniter中为空字符串

雷迪

我正在运行一个插入查询,以将用户信息插入数据库。要插入的字段是用户名和电子邮件,电子邮件字段不是必填字段。

当输入中包含电子邮件时,查询运行良好,但是当我在电子邮件中未输入任何内容时,PDO错误始终会报告键“ email”的错误“ Duplicate entry ”。

 $post = $this->input->post();

 $sql = "INSERT INTO users (username, email) VALUES (:username, :email)";

 $query = $this->db->conn_id->prepare($sql);

 $query->bindValue (':username', $post['username'], PDO::PARAM_STR);

 if ($email == false){
     $query->bindValue(':email', '', PDO::PARAM_STR );
 } else {
     $query->bindValue(':email', $post['email'], PDO::PARAM_STR );
 }

 $query->execute();
马克·米勒

首先,正如我在评论中提到的那样,您需要将email列设置为允许空值。如果您不需要电子邮件地址,则最好将非电子邮件存储为null而不是空字符串-但在这种情况下,因为列是唯一的,所以有必要。

然后,尝试以下代码:

$post = $this->input->post();
if (!$post['email']){
    $post['email'] = NULL;
}
$sql = "INSERT INTO users (username, email) VALUES (:username, :email)";
$query = $this->db->conn_id->prepare($sql);
$query->execute(array($post['username'], $post['email']));

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章