0

I have a dataset similar to the example below:

a, b, c
1, 4, 7
2, 5, 8
3, 6, 9

What I want to do is filter this data, based on a column that I previously selected. For example:

In column 'a', search for 2.

I have tried creating a variable for the given columns and attaching it to the WHERE MySQL function.

This is my form:

<form action="buscar.php" method="get">
        <input type="text" name="search" placeholder="">
            <select name="level">
                <option value="">Select an option</option>
                <option value="a">a</option>
                <option value="b">b</option>
                <option value="c">c</option>
            </select>
        <input type="submit" value="Procurar"> 
        </form>

This is my PHP/MySQL search code:

$level = $_GET['level'];
$search = $_GET['search'];
$result_search = "SELECT * FROM insects WHERE '$level' LIKE '%$search%';
$resultado_search = mysqli_query($conexao, $result_search);

When i do something like:

$result_search = "SELECT * FROM insects WHERE a LIKE '%$search%';

OR

$result_search = "SELECT * FROM insects WHERE b LIKE '%$search%';

It searches on the column that I'm indicating, which is what I want, but when I put:

$result_search = "SELECT * FROM insects WHERE '$level' LIKE '%$search%';

it shows nothing.

In the end, what I want is that the user have the ability to search in which column the given text will be used for the search.

1 Answers1

1

You last output is :

$result_search = "SELECT * FROM insects WHERE '$level' LIKE '%$search%';

Which translate in SQL to :

SELECT * FROM insects WHERE 'a' LIKE '%$search%

And what you are trying to achieve is :

SELECT * FROM insects WHERE a LIKE '%$search%

So you have to remove the quote around $level, like this :

$result_search = "SELECT * FROM insects WHERE $level LIKE '%$search%';

And I hate to be that guy, but you should look into SQL INJECTION

Dylan KAS
  • 4,840
  • 2
  • 15
  • 33
  • Thanks for such a quick answer, Dylan, It has worked! At this moment I'm just starting on PHP/MySQL, so will definitely take a look on your reading sugestion! – Pedro Schimmelpfeng Jul 01 '19 at 12:22
  • Glad it worked, don't hesitate to validate the answer if it was the proper answer to your question. – Dylan KAS Jul 01 '19 at 12:30