How can I replace HTML in MySQL?

I want to find and replace (or more accurately, append) some HTML in one of my MySQL database fields, where the field contains a specific string of text.

I can successfully find the relevant records using this query:

Read More
SELECT *
FROM `wp_posts`
WHERE `post_content` LIKE '%some phrase%'

This query returns all the records I want to append HTML to.

So I try the following query to append the HTML I want to use:

SELECT *
FROM `wp_posts`
WHERE `post_content` LIKE '%some phrase%'
UPDATE wp_posts SET post_content = REPLACE(post_content, '</strong></a>', '</strong></a>
<strong>Some additional piece of text</strong></p>')

But an error is returned:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE wp_posts SET post_content = INSERT(post_content, '&lt;/strong&gt;&lt;/a&gt;​', '&lt;/stro' at line 4

I presume it doesn’t like how I’ve formatted my HTML, but how should it be formatted?

Related posts

Leave a Reply

5 comments

  1. you are trying to execute two different queries. My guess is that you need to execute the following one:

    UPDATE wp_posts SET post_content = REPLACE(post_content, '</strong></a>', '</strong></a>
    <strong>Some additional piece of text</strong></p>') 
    WHERE `post_content` LIKE '%some phrase%'
    
  2. look on UPDATE Syntax , need to be like

    UPDATE wp_posts
    SET post_content = REPLACE(post_content, '</strong></a>', '</strong></a>
    <strong>Some additional piece of text</strong></p>')
    WHERE `post_content` LIKE '%some phrase%'
    
  3. Have you tried using the select as an inner query? (assuming

    UPDATE wp_posts SET post_content = REPLACE(post_content, '</strong></a>', '</strong></a>
    <strong>Some additional piece of text</strong></p>') 
    
    WHERE id in (SELECT id
    FROM `wp_posts`
    WHERE `post_content` LIKE '%some phrase%')
    
  4. There’s nothing wrong with the content you’re trying to replace. However, the way I see it, you construct your update query the wrong way: You put a SELECT right before an UPDATE query, probably expecting the UPDATE would only touch the SELECTed rows.

    I think what you want is this:

    UPDATE wp_posts 
        SET post_content = REPLACE(
            post_content,
            '</strong></a>',
            '</strong></a><strong>Some additional piece of text</strong></p>'
        )
    WHERE `post_content` LIKE '%some phrase%'