views:

119

answers:

2

i got this SQL query where post_title taken from $_GET

$sql = "SELECT ID FROM posts WHERE posts.post_title = '5-design-web-colourful'";

What is the best way to sanitize this and make it more safe ?

EDIT : (as requested) I'm trying to create a plugin that work to hide a particular category (named private) and all of its post for every non-logged guest. i have hook into 'pre_get_posts' and 'posts_selection' able to control how to show particular posts and category for admin, the member who wrote them, other member, and guest.

The category must be non exist. so it can not be shown on cat archive page in front end.

I know it's not relatedto the question cause what iask just how to sanitize name / title of a post. nothing more.

+2  A: 

Use mysql_real_escape_string, assuming you use MySQL.

Franz
For the string you insert only, I may add:`... $wpdb->posts.post_title = '".mysql_real_escape_string($str)."'";`
Franz
+2  A: 

While this doesn't directly answer your question, the better approach is to use bind parameters. This protects you from all attack vectors of this category.

http://php.net/manual/en/pdo.prepared-statements.php

http://www.php.net/manual/en/pdostatement.bindparam.php

For your example:

$sth = $dbh->prepare("select id from $wpdb->posts where $wpdb->posts.post_title = ?");
$sth->bindParam(1, $str);
$sth->execute();

CAUTION: This assumes that $wpdb is safe!

Anonymouse
seems to me that the OP meant this, though.
Josh