mysql — PHP, sql Динамический запрос с возможными LIKE, OR и AND, вместе взятые, работает неправильно

У меня есть форма поиска (поиск недвижимости, недвижимости):

HTML: метки опущены

 <input type="text" name="keywords" placeholder="keywords"/>

<select name="status" id="select-property-status" class="search-select">
<option value="" selected="selected">Tous</option>
<option value="1">Sale</option>
<option value="0">Rent</option>
</select>

<select name="type" id="select-property-type" class="search-select">
<option value="" selected="selected">Tous</option>
<option value="appartement">Appartement</option>
<option value="duplex">Duplex</option>
<option value="studio">Studio</option>
<option value="villa">Villa</option>
</select>

<select name="emplacement" id="select-property-emplacement" class="search-select">
<option value="" selected="selected">Tous</option>
<option value="La Goulette">La Goulette</option>
<option value="Gammarth">Gammarth</option>
<option value="La Marsa">La Marsa</option>
<option value="El Mourouj">El Mourouj</option>
</select>

<input name="surface_min" type="text" placeholder="min" value=""  />
<input name="surface_max" type="text" placeholder="max" value=""  />

<input name="rooms_min" type="text" placeholder="min" value=""  />
<input name="rooms_max" type="text" placeholder="max" value=""  />

<input name="price_min" type="text" placeholder="Prix min" value=""  />
<input name="price_max" type="text" placeholder="Prix max" value=""  />

<input type="hidden" name="search_form" value="True" required="required"/>
<input type="submit" name="submit" value="Search"  class="search-button" />

Сейчас search-results.php:

    // Saving search terms in variables
$keyword = strtolower(htmlspecialchars($_POST['keywords'])); // string from text field
$status = htmlspecialchars($_POST['status']); // 0 or 1
$type = htmlspecialchars($_POST['type']); // string value from option
$emplacement = htmlspecialchars($_POST['emplacement']); // string value from option
$surface_min = htmlspecialchars($_POST['surface_min']); // integer from text field
$surface_max = htmlspecialchars($_POST['surface_max']);// integer from text field
$chambres_min = htmlspecialchars($_POST['rooms_min']);// integer from text field
$chambres_max = htmlspecialchars($_POST['rooms_max']);// integer from text field
$prix_min = htmlspecialchars($_POST['price_min']);// integer from text field
$prix_max = htmlspecialchars($_POST['price_max']);// integer from text field

// create an empty array
$where_array = array();

// if user type in or choose an option in the search form
// > create a string with its value and put it in $where_array
if($keyword != '') $where_array[] = ' LOWER(prop_title) LIKE "%'.$keyword.'%" OR LOWER(prop_desc) LIKE "%'.$keyword.'%"';
if($status != '') $where_array[] = 'prop_status = '.$status.'';
if($type != '') $where_array[] = 'prop_type = "'.$type.'"';
if($emplacement != '') $where_array[] = 'prop_place = "'.$emplacement.'"';
if($surface_min != '') $where_array[] = 'prop_surface >= '.$surface_min.'';
if($surface_max != '') $where_array[] = 'prop_surface <= '.$surface_max.'';
if($rooms_min != '') $where_array[] = 'prop_rooms >= '.$rooms_min.'';
if($rooms_max != '') $where_array[] = 'prop_rooms <= '.$rooms_max.'';
if($price_min != '') $where_array[] = 'prop_price >= '.$price_min.'';
if($price_max != '') $where_array[] = 'prop_price <= '.$price_max.'';

// join all the array elements (the strings) saved in $where_array by the string : AND
$where_string = implode(" AND ", $where_array);

// the sql query
$search = "SELECT * FROM proprietes WHERE $where_string";
$search = $db->query($search);

// if the query exists
if($search)
{
// loop through all the properies that matches the WHERE conditions
foreach($search as $search_result)
{
// echo the title of the property
echo htmlspecialchars($search_result['prop_title']);
}
}
else
{
// which one is right ?
echo 'Error occured !';
echo 'No property found !';
}

Эта проблема

Все поля поиска работают нормально, если они выбраны отдельно, все комбинации работают нормально, кроме:
Ключевое слово И поля состояния, возвращенные данные из таблицы свойств, где это не должно быть: я поместил слово «вилла» в текстовое поле, затем выбрал только «Продажа» в поле выбора (продажа = 1, аренда = 0), но результат дал мне все виллы на продажу и в аренду! я использовал $search->debugDumpParams(); повторить это:

SELECT * FROM proprietes WHERE LOWER(prop_title) LIKE "%villa%" OR LOWER(prop_desc) LIKE "%villa%" AND prop_status = 1

Я думаю, что и моя логика, и синтаксис неверны! Любая помощь, пожалуйста?

Спасибо.

0

Решение

Я думаю, что если вы измените эту строку кода на

if($keyword != '')
$where_array[] = ' (LOWER(prop_title) LIKE "%'.$keyword.'%" OR LOWER(prop_desc) LIKE "%'.$keyword.'%")';

это исправит ваш запрос.

Это также может быть более читабельным, если вы используете двойные кавычки, то вам не нужно все . конкатенация и код становится немного легче для чтения.

if($keyword != '')
$where_array[] = " (LOWER(prop_title) LIKE '%$keyword%' OR LOWER(prop_desc) LIKE '%$keyword%')";
1

Другие решения

Здесь много всего, но ваш выходной запрос показывает проблему.

Неуказанные логические критерии ( AND а также OR) используются неправильно. Так должно быть больше

SELECT * FROM proprietes
WHERE prop_status = 1
AND (LOWER(prop_title) LIKE "%villa%" OR LOWER(prop_desc) LIKE "%villa%")

Вам нужно будет изменить свою логику в своих массивах, чтобы вести себя так. Другими словами, везде, где у вас есть OR в вашем запросе он должен быть заключен в скобки

1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector