1

I have a table called my_table with 2 fields ID and dbtext.

The fields in the database are:

ID: 1 dbtext: Hi this is Bobby's Stuff

I am trying to find and replace text within the dbtext field. Here is my code:

$findtext = 'Hi this is Bobby\'s Stuff';
$replacetext = 'Hi this is Larry\'s Stuff';

$findtext = stripslashes($findtext);
$replacetext = stripslashes($replacetext);



  $sql = "UPDATE my_table SET dbtext = REPLACE(dbtext,'" . $findtext . "','" . $replacetext . "') WHERE ID = '" . $ID . "' ";
$wpdb->query($sql);

Unfortunately when I strip the slashes, the query won't run due to the single quotes breaking the query.

However, if I don't strip the slashes, the query wont find a match as there is no slash in the database.

How do I handle this and make sure it will work with single quotes and double quote situations?

1
  • If performance is not critical for this task, consider fetching the rows and updating via wpdb::update(). Calling entire string queries asks for trouble. Commented Aug 1, 2020 at 1:30

1 Answer 1

1

Mysql follows triple-slash pattern for extra security. Try the code below

$findtext = 'Hi this is Bobby\\\'s Stuff';
$replacetext = 'Hi this is Larry\\\'s Stuff';

  $sql = "UPDATE my_table SET dbtext = REPLACE(dbtext,'" . $findtext . "','" . $replacetext . "') WHERE ID = '" . $ID . "' ";
$wpdb->query($sql);
Sign up to request clarification or add additional context in comments.

3 Comments

The triple slash worked when I added them manually. Trying to sort out how to add them dynamically though. Tried $findtext = preg_replace('(/\\\\/)','(/\\/)',$findtext); Plus other versions of this, but not having any luck.
@CRAIG You can also use this $e = str_replace("'", "\\\\\'",$findtext);

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.