Jump to content

Insert or Update Function Ajax


unemployment

Recommended Posts

Is there any way to tell my php ajax file to run the update query if the data already exist and if not, then create the row in the database?  I have both the update and the insert functions created, but was just wondering if I could tell php which one to use without passing through a parameter.

Link to comment
https://forums.phpfreaks.com/topic/257372-insert-or-update-function-ajax/
Share on other sites

You would use an INSERT .... ON DUPLICATE KEY UPDATE ... query. See the example in this post - http://www.phpfreaks.com/forums/index.php?topic=354126.msg1672540#msg1672540

 

Thanks for the suggestion.  I can't seem to get it working though. It inserts a row everytime.  I only want it to insert a row if one doesn't already exist and I want it to update the row if $int changes.  What am I doing wrong?

 

<?php

public function send_pitch_feedback($cid, $gid, $int)
{	
$cid = (int)$cid;
$gid = (int)$gid;
$int = (int)$int;

mysql_query("INSERT INTO pitches_feedback (user_id, company_id, group_id, creation_time, interest) VALUES ({$GLOBALS['user_info']['uid']}, ${cid}, ${gid}, NOW(), ${int})
ON DUPLICATE KEY UPDATE interest = ${int}");
}

?>

 

Probably not... Do you mean that I need to set like an index, or like a primary key? I don't really understand.

 

I can't just choose to update the query if the primary key is the same. 

 

This was the only update query I had.  I need to update the query if all of the WHERE clause is met.

 

<?php

public function update_pitch_feedback($cid, $gid, $int)
{	
$cid = (int)$cid;
$gid = (int)$gid;
$int = (int)$int;

$sql = "UPDATE `pitches_feedback` SET
			`interest` 	= {$int}
		WHERE `company_id` = ${cid}
		AND `user_id` = {$GLOBALS['user_info']['uid']}
		AND group_id = ${gid}";

return mysql_query($sql) or die(mysql_error());
}

?>

you could just first do a check to see if their user ID exists and if it does update else insert.

 

 

here is another idea

 

$result = mysql_query("update test set col='test' where col_id='1';");		 
if (mysql_affected_rows()==0) {
$result = mysql_query("insert into test (col_id, col) values ('1','test');");
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.