简体   繁体   English

从SQL结果中搜索PHP数组

[英]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. 我目前在php中有一个存储产品名称的数组,通常是5 - 10.我想创建一些SQL查询的结果与数组匹配的东西,以确保它们都是正确的,如果不是显示错误。

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? 我相信我需要在查询结果中加入某种while循环并在while循环中检查数组?

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; 您可以在使用while循环从db接收结果时循环,并使用in_array函数检查结果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). 您的数组包含产品名称($ products)和查询结果($ 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;
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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