使用 PDO 和 Mysql 检查数组中是否存在记录

Check if a record exists in an array using PDO and Mysql

我正在尝试在我的 mysql 中获取一条记录,无论该记录是否存在于数组中。我在网上搜索了有关使用 array_key_exists 函数的信息,不幸的是它总是给我 "Match not found" 即使记录存在于数组中。

这是我的输出。

Array ( [0] => Array ( [0] => Array ( [GUESTCHECK] => 10017 [0] => 10017 ) [1] => Array ( [GUESTCHECK] => 10024 [0] => 10024 ) [2] => Array ( [GUESTCHECK] => 10066 [0] => 10066 ) [3] => Array ( [GUESTCHECK] => 10084 [0] => 10084 ) [4] => Array ( [GUESTCHECK] => 10150 [0] => 10150 ) [5] => Array ( [GUESTCHECK] => 10154 [0] => 10154 ) [6] => Array ( [GUESTCHECK] => 10223 [0] => 10223 ) [7] => Array ( [GUESTCHECK] => 10224 [0] => 10224 ) [8] => Array ( [GUESTCHECK] => 10225 [0] => 10225 ) [9] => Array ( [GUESTCHECK] => 10261 [0] => 10261 ) [10] => Array ( [GUESTCHECK] => 10284 [0] => 10284 ) [11] => Array ( [GUESTCHECK] => 10298 [0] => 10298 ) [12] => Array ( [GUESTCHECK] => 20012 [0] => 20012 ) [13] => Array ( [GUESTCHECK] => 20014 [0] => 20014 ) [14] => Array ( [GUESTCHECK] => 20054 [0] => 20054 ) [15] => Array ( [GUESTCHECK] => 20056 [0] => 20056 ) [16] => Array ( [GUESTCHECK] => 20061 [0] => 20061 ) [17] => Array ( [GUESTCHECK] => 20131 [0] => 20131 ) [18] => Array ( [GUESTCHECK] => 20160 [0] => 20160 ) [19] => Array ( [GUESTCHECK] => 20163 [0] => 20163 ) [20] => Array ( [GUESTCHECK] => 20183 [0] => 20183 ) ) ) 

帮助我告诉我我的代码有什么问题?

  $gchecksummary = "SELECT DISTINCT GUESTCHECK FROM `items` 
where CODE = 771012 and DATE = '1/1/2018' or CODE = 771013 
and DATE = '1/1/2018' or CODE = 782012 
and DATE = '1/1/2018' or CODE = 774012 
and DATE = '1/1/2018' or CODE = 775203 
and DATE = '1/1/2018' or CODE = 775202 and DATE = '1/1/2018'";
$execgchecksummary  = $conn->prepare($gchecksummary);
$execgchecksummary->execute();


while($fetchgchecksummary = $execgchecksummary->fetchAll()){

$results[] = $fetchgchecksummary;

} 


 print_r($results);
 echo "<br />";

 if (array_key_exists("10017", $results))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }

问题出在您的代码逻辑和 sql 查询中。

为什么要获取不需要的行的数组并在其中进行查找?

您还多次重复具有相同值的 DATE 条件

您可以在查询中为 GUESTCHECK 定义条件,然后检查结果计数并执行 fetchAll(如果需要数据)。

行数据示例:

  $query = "
    SELECT * 
    FROM `items` 
    WHERE 
     GUESTCHECK = 10017 
      AND
     CODE IN (771012, 782012, 774012, 775203, 775202) 
      AND
     DATE = '1/1/2018'
  ";

  $statement = $conn->prepare($query);
  $statement->execute();

  if ($statement->rowCount() > 0)
  {
    echo "Match found";

    $items = $statement->fetchAll();
    var_dump($items);
  }
  else
  {
    echo "Match not found";
  }

没有从数据库中获取行的示例:

  $query = "
    SELECT 1
    FROM `items` 
    WHERE 
     GUESTCHECK = 10017 
      AND
     CODE IN (771012, 782012, 774012, 775203, 775202) 
      AND
     DATE = '1/1/2018'
    LIMIT 1
  ";

  $statement = $conn->prepare($query);
  $statement->execute();

  if ($statement->rowCount() > 0)
  {
    echo "Match found";
  }
  else
  {
    echo "Match not found";
  }

p.s。确保您已将索引添加到 GUESTCHECKCODE 字段以帮助数据库引擎有效地搜索数据。