mcmuney Posted April 13, 2010 Share Posted April 13, 2010 I'm looking for an UPDATE SQL statement that will allow me to replace a portion of the field. For example, if I have a field that has this content, "The apple is red" and I want to update only "red" with "blue". Btw, this will be a mass update. Thanks in advance. Quote Link to comment Share on other sites More sharing options...
Domcsore Posted April 13, 2010 Share Posted April 13, 2010 Try something like: Getting the string from the database and then using the str_replace function and then updating it. Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 13, 2010 Share Posted April 13, 2010 UPDATE `table` SET `fieldname` = REPLACE(`fieldname`, 'red', 'blue') Quote Link to comment Share on other sites More sharing options...
Domcsore Posted April 13, 2010 Share Posted April 13, 2010 For example: $result = mysql_query("SELECT * FROM Persons WHERE FirstName='Peter is my name' "); $row = mysql_fetch_array($result); $replace = str_replace('Peter', 'Jammy', $row['FirstName']); mysql_query("UPDATE Persons SET FirstName = '$replace' WHERE FirstName = 'Peter' "); Something like that should set first name to 'Jammy is my name' where 'Peter is my name' was. Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 13, 2010 Share Posted April 13, 2010 For example: $result = mysql_query("SELECT * FROM Persons WHERE FirstName='Peter is my name' "); $row = mysql_fetch_array($result); $replace = str_replace('Peter', 'Jammy', $row['FirstName']); mysql_query("UPDATE Persons SET FirstName = '$replace' WHERE FirstName = 'Peter' "); Something like that should set first name to 'Jammy is my name' where 'Peter is my name' was. This SINGLE query would accomplish the same thing as that code above! UPDATE Persons SET FirstName = REPLACE(FirstName, 'Peter', 'Jammy') WHERE FirstName='Peter is my name' No need to query the database for the records, process the records, and then do an update. Quote Link to comment Share on other sites More sharing options...
Domcsore Posted April 13, 2010 Share Posted April 13, 2010 Haha, yeah I didn't know about that command if you look at the times I posted it at around the same time you posted yours. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.