Reputation: 57
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
Reputation: 780723
You have several problems.
You're not escaping the input, so you're subject to SQL injection or syntax errors.
You need to put quotes around the LIKE
parameter.
You're overwriting $var
each time through the loop instead of appending to it.
You're not putting any spaces around the expression.
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