A
A
Alexander Andropov2019-12-18 16:00:51
PHP
Alexander Andropov, 2019-12-18 16:00:51

How to check value in multiple columns at once?

Good day.
There is a text input where the user enters an address.

<input type="text" name="address" placeholder="Улица, Район, Округ">

How to write a query correctly so that the values ​​in this field are searched for several columns in the database table at once?
I do it like this:
$query = "SELECT * FROM `objects` WHERE `bid_type`='$bid_type' AND `object_type`='$object_type' AND `address` LIKE '%$address%' AND `okrug` LIKE '%$address%'";

But constantly comes false as a result.
How to write a query correctly so that the value in input is searched for in three or four columns at once and all the results found are displayed

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
idShura, 2019-12-18
@LongOf

If the bid_type and object_type fields do not apply to address and okrug , then so:

SELECT * FROM `objects` 
 WHERE `bid_type`='$bid_type' 
   AND `object_type`='$object_type' 
   AND (`address` LIKE '%$address%' 
    OR `okrug` LIKE '%$address%')

A
Artem Ivanov, 2019-12-18
@ns174ru

Replace all AND with OR
And you will have "Happiness"

F
FanatPHP, 2019-12-18
@FanatPHP

All beginners without exception think that their query is applied to the entire database at once.
Well, they want to find lines where both the address and the county are equal to some value.
But if you think about it, then the query compares each row individually with the condition.
And AND will look for a string in which both the address and the county are equal to this value.
Whereas they want to return every row in which the address OR the county was equal to some value.
That is, instead of AND when searching "in several columns" you need to use OR.
Of course, this does not apply to other conditions used in the request. They remain as they are, and the search "in several fields" is simply taken in brackets.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question