raghuveer999
raghuveer999

Reputation: 709

SQL query implementing AND functionality with PHP array

I am using PHP with MySql. I need a query which should fetch me results according to my requirements.

I have a table property_features_table which has properties with some features.

In the front end I have a search functionality. When a user selects multiple features suppose balcony,wifi,2-bedroom etc., He should be shown with properties having ALL the features he selected.

But when I use the following code, I am getting results (properties) which has atleast one of the features.

$featuresString = implode("','",$features);
$featuresString = "'".$featuresString."'";
$query = " SELECT * FROM property_features_tbl WHERE property_features_tbl.feature_id in (".$featuresString.")";

$features is an array which contains user selected features.

I want to display properties which has all the features selected by the user. Help me in writing the query.

Upvotes: 0

Views: 91

Answers (1)

Kickstart
Kickstart

Reputation: 21513

Assuming you just want the property ids, then something like this:-

<?php

$featuresString = implode("','",$features);
$featuresString = "'".$featuresString."'";
$feature_count = count($features);
$query = " SELECT property_id, COUNT(*) AS feature_count 
        FROM property_features_tbl 
        WHERE property_features_tbl.feature_id in (".$featuresString.")
        GROUP BY property_id
        HAVING feature_count = $feature_count";

?>

Upvotes: 1

Related Questions