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

时间:2018-07-14 11:05:10

标签: php arrays pdo array-key-exists

我试图在我的mysql中获取一条记录,无论记录是否存在于数组中。我已经在网上搜索了有关使用array_key_exists函数的信息,但是不幸的是,即使记录存在于数组中,它也总是给我“找不到匹配项”。

这是我的输出。

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";
  }

1 个答案:

答案 0 :(得分:1)

问题出在您的代码逻辑和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字段中,以帮助数据库引擎有效地搜索数据。