3

I have a WordPress plugin that at one point I need to see if a certain title exists in the database. For 2 years, this code worked fine:

$myposttitle= $wpdb->get_results(
 "select post_title from $wpdb->posts
  where post_title like '%".  mysql_real_escape_string($myTitle) . "%'"
);

However, with php 5.5. and WP 3.9.1, this causes an error because the function mysql_real_escape_string is deprecated.

Any ideas on what other function will properly escape the contents of $myTitle now that I can't use mysql_real_escape_string anymore?

Thanks

2

When working with database in WordPress you should never use the low lever mysql_* or mysqli_* functions.

Always use $wpdb methods, in your case you should use prepare():

$query = $wpdb->prepare(
  "SELECT post_title from $wpdb->posts
  WHERE post_title LIKE %s",
  "%" . $myTitle . "%"
);

Moreover, once you are getting a single column, you have easier life using get_col instead of get_results:

$myposttitle = get_col( $query );
  • Thanks... much appreciated. However, this won't handle the escape issue I mentioned, will it? – Allen May 20 '14 at 17:53
  • @Allen yes, prepare escape the values using mysqli_real_escape_string (PHP 5.5 compatible) or mysqli_real_escape_string according to your current version of PHP. – gmazzap May 20 '14 at 22:41
5

While the prepare() answer given is partially correct, if you do need a way to escape a string for an SQL statement manually, use esc_sql().

For the specific case of escaping a string to be placed inside a like statement, then it should more correctly be written like this:

$query = $wpdb->prepare(
  "SELECT post_title from $wpdb->posts
  WHERE post_title LIKE %s",
  "%" . $wpdb->esc_like( $myTitle ) . "%"
);

The $wpdb->esc_like() is necessary so as to properly escape any percent signs, underscores, or backslashes that may be in the phrase being searched for. Note that $wpdb->esc_like() does not return prepared input, it only escapes the special characters used in a LIKE. Thus, the prepare() is still needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.