Replace a string inside of a MYSQL field

I recently needed to replace part of a URL found inside the body HTML of a page that was stored in a MySQL column.  In order to do this I was able to use the handy Replace() MySQL function.

UPDATE myPage
SET pageBody = REPLACE(pageBody, '/oldirectory', '/newdirectory')
WHERE INSTR(pageBody, '/olddirectory') > 0;

The INSTR() function is not technically needed, but it prevents MySQL from doing an update on every row regardless of if the string is found.

Leave a Reply

Your email address will not be published. Required fields are marked *