php - Mysqli searching value in multiple fields

181

I am trying to figure out how to search for Value1 that could be in Field1, Field2 or Field3. I know my syntax is wrong because it's obviously not working, but here was my crack at it:

$query = "SELECT *
   FROM table1
  WHERE city = '$city'
    AND state = '$state'
    AND location = '$location'
    AND (field1 = '$field1U' OR field1 = '$field2U' OR field1 = '$field3U')
  ORDER BY date_created LIMIT 5";
$data = mysqli_query($dbc, $query);

I thought maybe I could use where field1 in (1,2,3) but I couldn't get it to work. Any help would be greatly appreciate.

281

Answer

Solution:

If you want to find all of the records where:

field1 = someValue

orfield2 = someValue

orfield3 = someValue

then you can use this:

  $query = "SELECT * FROM table1 WHERE city = '$city' AND state = '$state' AND    location = '$location' AND (field1 = '$Value1' OR field2 = '$Value1' OR field3 = '$Value1') ORDER BY date_created LIMIT 5";
    $data = mysqli_query($dbc, $query);
723

Answer

Solution:

Replace

AND (field1 = '$field1U' OR field1 = '$field2U' OR field1 = '$field3U')

with

AND (field1 = '$search' OR field2 = '$search' OR field3 = '$search')

(notice i'm searching for field1, field2 or field3) but please, please, please (!!) escape those $search strings! for example:

$search = mysqli_real_escape_string($link, $search)

where $link was set using

$link = mysqli_connect(...)

please refer to http://php.net/manual/de/mysqli.real-escape-string.php this is used to prevent SQL Injection (https://en.wikipedia.org/wiki/SQL_injection)

oh, and try to split the text from the variables, as i personally, think that's safer and better coding style. for your use case:

AND (field1 = '" . $search . "' OR field2 = '" . $search . "' OR field3 = '" . $search . "')

People are also looking for solutions to the problem: PHP script doesn't finish after large file download

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.