Reputation: 379
This code checks if $value
(array) is set in the database as 1
. The foreach loop saves all the founding matches into the array $products
. Now I have all the fields in the database which have the value 1
but that's not really what I want, because if the field 'dog' equals 1
and the field 'cat' equals NULL
, I still have the value of 'dog' in my array. It only should get to the array when BOTH equal 1.
For simple variables you can use the &&
or AND
operator to check if all keys have the same value but how do I do this with an array?
$products = array();
foreach($_POST['selected_checkboxes'] as $value) {
var_dump($value);
if($result = $db->query("SELECT * FROM produkte WHERE `$value` = 1")){
while($row = $result->fetch_object()) {
if (!in_array($row->name, $products)) {
array_push( $products, array('name'=>$row->name, 'image'=>$row->image, 'link'=>$row->link) );
}
}
}
else {
array_push($products, 'error');
}
}
Upvotes: 1
Views: 81
Reputation: 26
Change your SQL statement such that all checked values are equal to 1.
You can append a " = 1 AND "
to each value then use them in your query.
<?php
$arr = ['field1', 'field2', 'field3'];
$condition = join(' = 1 AND ', $arr) . ' = 1';
The output would be "field1 = 1 AND field2 = 1 AND field3 = 1"
. You can then use $condition
in your query.
$db->query("SELECT * FROM produkte WHERE $condition")
UPDATE:
To cope with fieldname containing spaces you would need to wrap each fieldname with backticks so change this line
$condition = '`' . join('` = 1 AND `', $arr) . '` = 1';
Upvotes: 1