CodeIgniter Forums
appending record instead of replacing field - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Libraries & Helpers (https://forum.codeigniter.com/forumdisplay.php?fid=11)
+--- Thread: appending record instead of replacing field (/showthread.php?tid=72658)



appending record instead of replacing field - richb201 - 01-19-2019

I am trying to update one field of a table.
PHP Code:
       $userid=$this->session->userdata('userid');
 
       $campaign=$this->session->userdata('campaign');
 
       $sql="SELECT * FROM users WHERE email = ?";
 
       $query $this->db->query($sql,$userid);
 
       $row $query->row();
 
       $iRc=$this->db->replace('users',array('campaign'=> $campaign)); 
I am finding that this is appending a new record onto the end of the table rather than replacing the campaign field if the userid matches. This is the table structure. What is the problem?


RE: appending record instead of replacing field - php_rocs - 01-19-2019

@richb201,

Based on the CI documentation ( https://www.codeigniter.com/user_guide/database/query_builder.html?highlight=join#updating-data ) replace is basically the SQL standard for (optional) DELETE + INSERT, using PRIMARY and UNIQUE keys...

What you need to do is what you stated in your first sentence. You need to do an update to the table on a specific column where email equals a specific email address.


RE: appending record instead of replacing field - richb201 - 01-19-2019

Thanks. I did see that. I was thinking that perhaps the issue was that the field I am trying to update is not primary. I did make it unique. You can see that the id is already primary and I can't have two primaries. Is there a better way to do this other than replace? Or should I manually do a delete and then an insert?


RE: appending record instead of replacing field - richb201 - 01-20-2019

I solved it by using:

$userid=$this->session->userdata('userid');
$campaign=$this->session->userdata('campaign');
$this->db->set('campaign', $campaign);
$this->db->where('email', $userid);
$this->db->update('users');


RE: appending record instead of replacing field - php_rocs - 01-21-2019

@richb201,

Perfect.