Why should the “____ is not there” message be displayed? There is nothing in this code that checks the WHY. Once that’s resolved (and the code updated correctly) it will only display 2/4 at any given time.
Why not just select the fields you need from the outset?
$tgt = array(1094, 1095);
$qry = "select product_id from cart_table where product_id IN (".join(',', $tgt).")";
// echo $qry; // debug
// spoofing your result set
$rows[0]['product_id'] = 1000;
$rows[1]['product_id'] = 1094;
foreach( $rows as $row ){
if( in_array($row['product_id'], $tgt ) ) {
echo $row['product_id'] . " is in the table";
}else{
echo $row['product_id'] . " is NOT in the table";
}
}
Seems several others have posted along these lines too, this just explains why your original code is flawed, with a bit of logical thinking
Look at your logic and think it over again.
First let’s consider the fact that you can simply your IF statements to
if($row['product_id'] == 1094)
{
echo "1094 is already there";
} else {
echo "1094 is not there";
}
if($row['product_id'] == 1095)
{
echo "1095 is already there";
} else {
echo "1095 is not there";
}
Now what if your cart_table contains the following product_ids: 1094 and 1095
When you loop through your records, you can easily see why it prints out all 4 messages. First record will produce 1094 is there and 1095 is not there, Second record will produce 1094 is not there and 1095 is there.
$tgt = array(1094, 1095);
$qry = “select product_id from cart_table where product_id IN (”.join(‘,’, $tgt).“)”;
// spoofing your result set
$rows[0][‘product_id’] = 1000; <– this row would NOT be returned by the query you just gave.
$rows[1][‘product_id’] = 1094;
If the table contained entries for 1094 and 1095, and you searched for 1000 and 1094, the code would only spit out “1094 is in the table”.
My understanding of the OP was that he wanted a response for all search items. (If this is incorrect, let me know lol)
Consider implementing array_intersect and array_diff.
//Assume table holds entries for 1094,1095.
$srch = array(1000,1094);
$qry = "select product_id from cart_table where product_id IN (".join(',', $srch).")";
//fetch_assoc the results, stripping the values into $rows.
//$res = $db->query($qry);
//while($row = $res->fetch_assoc()) {
// $rows[] = $row['product_id'];
//}
//Spoofing the result:
$rows[0] = 1094;
//Only one result, because 1000 isnt in the table.
$in_table = array_intersect($srch,$rows);
$out_table = array_diff($srch,$rows);
if(count($in_table) > 0) {
echo implode(',',$in_table)." are in the table already.<br />";
}
if(count($out_table) > 0) {
echo implode(',',$out_table)." are not in the table already.<br />";
}