1

I'm attempting to replace particular text strings in multiple tables and fields. I have code to do it for one field in one table, but I don't want to duplicate my efforts (since I have many strings I'd like to replace).

Here's my code for one field in one table:

UPDATE `phpbb3`.`phpbb_posts`
SET `post_subject` = REPLACE(`post_subject`,'string-to-be-replaced','replacement-string')
WHERE ( `post_subject` LIKE '%string-to-be-replaced%' )
ORDER BY `phpbb_posts`.`post_time` DESC

How do I write a command to replace text in both the phpbb_posts.post_subject field and the phpbb_topics.topic_title field?

(Do I need the WHERE or ORDER, since phpMyAdmin doesn't show the results of an UPDATE anyway?)

1
  • You don't need the ORDER BY clause, but I'm not sure why you wouldn't need to use a WHERE clause because of phpMyAdmin. UPDATE queries without a WHERE clause affect all rows in the table, so they're generally a bad idea. In this specific instance it may not matter much, because MySQL will be using the replace function to look for string-to-be-replaced and only replace this in any matching rows. But generally, a WHERE clause is the most important thing of an UPDATE query. You don't want all of your users' passwords to be changed because one user changed his password. Commented May 20, 2012 at 21:36

1 Answer 1

2

You can't update multiple tables in one statement, however, you can use a transaction to make sure that two UPDATE statements are treated together. You can also batch them to avoid a round trip.

BEGIN TRANSACTION
UPDATE phpbb_posts
SET post_subject = REPLACE(`post_subject`,'string-to-be-replaced','replacement-string')
WHERE ( `post_subject` LIKE '%string-to-be-replaced%' )
ORDER BY `phpbb_posts`.`post_time` DESC

UPDATE phpbb_topics
SET .topic_title = <something>
WHERE <column> = <something>

COMMIT
Sign up to request clarification or add additional context in comments.

2 Comments

You probably meant to write "can't" :)
@Daan - Corrected it. Thanks for spotting it and reporting it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.