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