简体   繁体   中英

Search PHP Array from results of SQL

I currently have an array in php that stores product names, normally 5 - 10. I would like to create something where the results of a SQL query is matched against the array to make sure they are all correct, and if not to show an error.

So far I have put the results into an array, then ran the query to get the results. I believe I need to put some sort of while loop with the results of the query and check the array in that while loop?

You can cycle while receiving results from db with a while loop and checking results with the in_array function http://php.net/manual/en/function.in-array.php $availability = 0;

$cart_products = array("book", "album");
$available_products = array();

while($row = mysql_fetch_array($result)) {
    $available_products[] = $row['product'];
}

foreach($cart_products as $key => $value){  
    if (in_array($value, $available_products)){
       $availability = 1;
    }
} 

You have the array with the product name($products) and the results of the query($row). While you loop trough the results you can check if the element is present,otherwise echo error and break the loop:

While(...) {     
    if(!in_array($row['retrivedprod'],$products)) {
        echo 'error';
        break;
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM