Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm having a bit of a brain fart on this one. I'm working on some code that resembles a custom search form. The custom search form, is a mixture of checkboxes as well as some drop downs. All of the fields which are being searched for are also custom fields. The custom fields were entered through a custom write panel. Some of the fields are single values others are serialized fields.

The current code works, but i'm not sure if should be taking another approach, i'm not looking for anyone to write code for me. I'm just looking for some ideas on how this could be better.

$city = $_REQUEST['sCity'];
$activity = $_REQUEST['sActivity'][0];
$riverSegment = $_REQUEST['sRiverSegment'];
$topicOfInterest = $_REQUEST['sTopicOfInterest'][0];

$querystr = "
SELECT DISTINCT wp_posts.* FROM wp_posts, wp_postmeta
WHERE (
 wp_posts.ID = wp_postmeta.post_id
 AND wp_postmeta.meta_key = 'city'
 AND wp_postmeta.meta_value = '$city'
) OR (
 wp_posts.ID = wp_postmeta.post_id
 AND wp_postmeta.meta_key = 'riverSegment'
 AND wp_postmeta.meta_value = '$riverSegment'
) OR (
 wp_posts.ID = wp_postmeta.post_id
 AND wp_postmeta.meta_key = 'topicOfInterest'
 AND wp_postmeta.meta_value LIKE '%$topicOfInterest%'
) OR (
 wp_posts.ID = wp_postmeta.post_id
 AND wp_postmeta.meta_key = 'activity'
 AND wp_postmeta.meta_value LIKE '%$activity%'
) AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'sites'
ORDER BY wp_posts.post_date DESC";

I feel like the above sample is flawed because if the first condition finds a match it will ignore the rest of the conditions.

Side Note: If i'm working with $wpdb->get_results(); should i still be escaping the user input to keep it clean?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

This doesn't seem especially complex, but does seem bulky and prone to errors.

As I answered couple of times on similar issues - if this isn't time critical then wait for WP 3.1 because it will have major improvements for querying by custom fields.

See Advanced Metadata Queries for brief writeup on upcoming improvements.

For sanitizing queries see $wpdb->prepare() method - Protect Queries Against SQL Injection Attacks.

share|improve this answer
    
I agree, that's why i was looking for some pointers. I'll move forward with the code as is, but i'll keep my post unanswered for a few hours to see if anyone else has dealt with this issue in a better fashion. Thanks for your response! –  Jealous Republic Dec 29 '10 at 19:41
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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