PHP how to update db record if already exits | codeigniter method

I’m trying to figure out how I can check to see if certain post array values exist in a db record before a new record is created. Here is my current insert method:

[php]
public function user_rates_image() {
$data = array(
‘user_id’ => $this->input->post(‘user_id’),
‘username’ => $this->input->post(‘username’),
‘image_id’ => $this->input->post(‘image_id’),
‘commercial’ => $this->input->post(‘commercial’),
‘clarity’ => $this->input->post(‘clarity’),
‘composition’ => $this->input->post(‘composition’),
‘charisma’ => $this->input->post(‘charisma’),
‘body’ => $this->input->post(‘body’),
‘mass’ => $this->input->post(‘mass’)
);

	$query = $this->db->insert('users_rate_table', $data);
	if ($query) {
		return true;
	} else {
		return false;
	}
}

[/php]

I’m going to go on a side tangent here, but what are you trying to accomplish?

The reason my I ask this is, if something already exists in your database, do you want to update it?

If so… do this…

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

[php]INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE table SET c=c+1 WHERE a=1;[/php]

If you want to ignore it all together if a duplicate key exists…

You can do this…

[php]INSERT IGNORE INTO table (a,b,c) VALUES (1,2,3);[/php]

This way you won’t have to add any checks in, just make sure your table has a primary key defined.

Sponsor our Newsletter | Privacy Policy | Terms of Service