Jump to content

mysql_update_id


The Little Guy

Recommended Posts

I have the following query:

$db->query(
"insert into songs
(artist_id, album_id, track_id, song_name) values ($artist_id, $album_id, $track, '$song')
on duplicate key update song_name = values(song_name)"
);

 

I know I can use mysql_insert_id on that, but what if there is a duplicate key, how can I get the key that was updated?

 

so, is there anything like a mysql_update_id?

Link to comment
https://forums.phpfreaks.com/topic/233209-mysql_update_id/
Share on other sites

Here's what I do.

 

ID is set to auto-increment in mysql

 

I do a select query to see if the value exists, if value exists I get the current id and make a variable of $check.

$sql_check = mysql_query("SELECT * FROM table WHERE value = '".$value."'");
$check = mysql_num_rows($sql_check);
$row = mysql_fetch_array($sql_check);
$the_ID = $row['ID'];

 

when doing the first check to see if the name is there you now have the row id, now run this if/else query

 

if($check > 0) {
mysql_query("UPDATE table SET value_one='$value_one', value_two='$value_two', value_three='$value_three' WHERE ID='$the_ID'");
echo "Updated id $the_ID";
} else {
//for inserts don't use id and let mysql auto-increment the id
mysql_query("INSERT INTO table (value_one,value_two,value_three)
VALUES ('$value_one', '$value_two', '$value_three')");
printf("Inserted id %d\n", mysql_insert_id());
}

Link to comment
https://forums.phpfreaks.com/topic/233209-mysql_update_id/#findComment-1199475
Share on other sites

Here's what I do.

 

ID is set to auto-increment in mysql

 

I do a select query to see if the value exists, if value exists I get the current id and make a variable of $check.

$sql_check = mysql_query("SELECT * FROM table WHERE value = '".$value."'");
$check = mysql_num_rows($sql_check);
$row = mysql_fetch_array($sql_check);
$the_ID = $row['ID'];

 

when doing the first check to see if the name is there you now have the row id, now run this if/else query

 

if($check > 0) {
mysql_query("UPDATE table SET value_one='$value_one', value_two='$value_two', value_three='$value_three' WHERE ID='$the_ID'");
echo "Updated id $the_ID";
} else {
//for inserts don't use id and let mysql auto-increment the id
mysql_query("INSERT INTO table (value_one,value_two,value_three)
VALUES ('$value_one', '$value_two', '$value_three')");
printf("Inserted id %d\n", mysql_insert_id());
}

 

That is basically what I resorted to.  Thanks guys!

Link to comment
https://forums.phpfreaks.com/topic/233209-mysql_update_id/#findComment-1199481
Share on other sites

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.