Friday, 15 January 2010

MySQL Update if value exists, Insert if not in PHP? -



MySQL Update if value exists, Insert if not in PHP? -

$sql_career = "replace career (id, battletag, lastheroplayed, lastupdated, monsters, elites, hardcoremonsters, barbarian, crusader, demonhunter, monk, witchdoctor, wizard, paragonlevel, paragonlevelhardcore) values ('', '$battletag', '$lastheroplayed', '$lastupdated', '$monsters', '$elites', '$hardcoremonsters', '$barbarian', '$crusader', '$demonhunter', '$monk', '$witchdoctor', '$wizard', '$paragonlevel', '$paragonlevelhardcore')";

id auto increments. battletag unique.

everything else changes on time. want replace or update entry if battletag exists without making new id. if doesnt exist want create new entry letting id auto increment unique battletag.

this works 1 problem:

$sql_career = " insert career (id, battletag, lastheroplayed) values (null, '$battletag', $lastheroplayed) on duplicate key update lastheroplayed=$lastheroplayed; ";

if i, instance, load in 2 unique rows, id auto increments 1 , 2 each. if load row has duplicate of unique key of 1 of existing rows (and updates should) triggers auto increment. if add together in 3rd unique row, number 4 instead of 3.

how can prepare this?

you want utilize on duplicate key ... update syntax instead of replace into.

define unique column (primary or unique index) check in statement this:

insert table (a,b,c) values (1,2,3),(4,5,6) on duplicate key update c=values(a)+values(b);

the benefit of using on replace replace delete info have , replace (sort of command name implies) info supplying sec time round. update on... statement update columns define in sec part of - if duplicate found - can maintain info in columns want maintain in.

basically command (abbreviated of import columns only)

$sql_career = " insert career (id, battletag, heroeskilled) values ($id, '$battletag', $heroeskilled) on duplicate key update heroeskilled=heroeskilled+1; ";

again, remember in table, need enforce unique column on battletag - either primary key or unique index. can 1 time via code or via phpmyadmin if have installed.

edit: okay, potentially found little gem (it's 3rd of way downwards page) might trick - never used myself though, can seek next me?

$sql_career = " insert ignore career (id, battletag, heroeskilled) values (null, '$battletag', $heroeskilled) on duplicate key update heroeskilled=heroeskilled+1; ";

there seems collaborating evidence supporting in this page of docs well:

if utilize insert ignore , row ignored, auto_increment counter not incremented , last_insert_id() returns 0, reflects no row inserted.

php mysql

No comments:

Post a Comment