Jump to content

[SOLVED] convert insert statement to update statement


trpplayer79

Recommended Posts

Dear,

 

I do a import from a sql file into my db.

but when the record already exists I would like to change the statement to a update statement.

I know you can us str_replace but the problem is that there is a different syntax for the 2 statements.

the insert statement syntax is: instert into table ( .., .., .., ) values (..., ..., ..., ...)

the update statement is:UPDATE table SET x=x-data [, y=y-data ...] WHERE where_condition

my problem is that i have no idea how to start the conversion of the insert statement to the update statement.

can someboy please help me (maybe with a standard script)?

 

Greetz

 

Trpplayer79

Link to comment
Share on other sites

I've found a solution but it isn't fail safe.

this is the code that does the conversion:

$update=trim($query);
$insrt="INSERT INTO Table (field1, field2, .... , remark) VALUES (";
$phrase = str_replace($insrt, "", $update);  /* remove "insert into .. ) values (" from the query to keep only the values */
$newphrase = str_replace(")", "", $phrase); /*removes the ")  at the end  */
$rem_pos = strrpos($newphrase, ", '"); /* get position just befor the remark */
$rem = substr($newphrase, $rem_pos+2); /* create the substring remarks */
/* split the  values into separete variables */
list ($field1value, $field2value, .... , $remark) = split(", ", $newphrase);
/* create the update statement for the different fields */
$upd = "field1".$field1Value.", field2=".$field2value.", ..... ", remarkfield=".$rem."";
/* place the insert statement together with the update statement */
$qry = $update." ON DUPLICATE KEY UPDATE ".$upd;
$query = trim($qry);

 

I had to get the remark with the substr because in the remark the pattern ", ".

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.