为了账号安全,请及时绑定邮箱和手机立即绑定

在 Codeigniter 中插入或更新条件

在 Codeigniter 中插入或更新条件

PHP
守着一只汪 2022-10-22 16:17:00
我有两个表(tb_account 和 tb_reg),它们有一个基于 user_id . user_id 用户注册帐户时 tb_account 已存在。我正在尝试在数据库中插入或更新一个表,但这取决于该行是否不存在,那么它将是 insert 新行。如果没有,它将 update 排。首先,用户必须 tb_reg 根据 user_id 它的成功填写几个表格。但是当他要第二次更新表格时,条件不起作用。我有这样的错误 Duplicate entry '23' for key 'user_id' 。这是我的模型:<pre>$pen = [            'tpt_lahir' => $post['tpt_lahir'],            'tgl_lahir' => $post['tgl_lahir'],            'agama' => $post['agama']        ];    $user_id=$this->session->userdata('userid');    //user_id in this session is from tb_account    $sql = "SELECT * FROM tb_reg WHERE user_id = '".$user_id."'";    $query = $this->db->query($sql);    if($query != $user_id) {        $this->db->set('user_id', $user_id);        $this->db->insert('tb_reg', $pen);     } else {        $this->db->where('user_id', $user_id);        $this->db->update('tb_reg', $pen);    }</pre>当然,问题来自条件(if else),但我无法修复它。任何人?提前致谢。
查看完整描述

1 回答

?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

你忘了调用 num_rows()函数你的代码应该是这样的


$sql = "SELECT * FROM tb_reg WHERE user_id = '".$user_id."'";

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

if($query->num_rows() == '0' ) {

    $this->db->set('user_id', $user_id);

    $this->db->insert('tb_reg', $pen); 

} else {

    $this->db->where('user_id', $user_id);

    $this->db->update('tb_reg', $pen);

}

希望这可以帮助


查看完整回答
反对 回复 2022-10-22
  • 1 回答
  • 0 关注
  • 84 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信