terf
terf

Reputation: 57

Dynamic MySQL query

I'm trying to create a dynamic sql query that compares my cat column to whatever the user entered in a form. The idea is that I will be able to take a dynamic array of values and then compare them to the cat column. This is what I tried to do:

// Loop to get the array of values from form
$get_arr = $_GET;
foreach ($get_arr as $get) {
    $var = "AND cat LIKE $get";
}
// SQL query
$sql = "SELECT * FROM items
WHERE title LIKE 'this'
AND description LIKE 'that'
'%$var%'";

It doesn't work -- $var always show up blank. What would the solution be?

Upvotes: 0

Views: 48

Answers (1)

Barmar
Barmar

Reputation: 780723

You have several problems.

  1. You're not escaping the input, so you're subject to SQL injection or syntax errors.

  2. You need to put quotes around the LIKE parameter.

  3. You're overwriting $var each time through the loop instead of appending to it.

  4. You're not putting any spaces around the expression.

  5. You're putting % around the whole $var, it should be inside the LIKE parameter.

foreach ($get_arr as $get) {
    $get = mysqli_real_escape_string($conn, $get);
    $var .= " AND cat like '%$get%'";
}

$sql = "SELECT * FROM items
        WHERE title LIKE '%this%'
        AND description LIKE '%that%'
        %var";

Upvotes: 2

Related Questions