CRAIG
CRAIG

Reputation: 1029

Replacing String with Apostrophe in MySQL When running a find and replace query

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?

Upvotes: 1

Views: 159

Answers (1)

Chilarai
Chilarai

Reputation: 1888

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);

Upvotes: 1

Related Questions