(PDO)将数据库数据插入数组并使用in_array来回显数据

时间:2018-04-07 20:41:32

标签: php pdo

我的问题是我无法从数据库中将数据插入到数组中,然后使用in_array函数回显出特定的字符串或文本。我究竟做错了什么?
这是我尝试过的代码。

<?php
try {
    $conn = new PDO('mysql:host=localhost; dbname=driving','root','');
    $sel = "SELECT first_name, civ_licenses FROM users";
    $stmt = $conn->prepare($sel);
    $stmt->execute();
    while($row = $stmt->fetch()) {
        $arrayResult = $row['civ_licenses'];
        $civArray = array($arrayResult);
        if(in_array('`license_civ_driving`,1', $civArray)){
            echo $row['first_name'], 'has got the driving license';
        }
    }
    die;
} catch (PDOException $e) {
  echo "There was an error with your code!" . $e->getMessage();
  exit;
}

 ?>

2 个答案:

答案 0 :(得分:0)

这就是我要做的事情

$sel = "SELECT first_name, civ_licenses FROM users";
$stmt = $conn->prepare($sel);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_GROUP);

它会给你这样的东西

 [
     'bob' => [
           ['civ_licenses1'],
           ['civ_licenses2'],
     ], 'alice' => [
       ....
     ]
 ]

它将它们分组在第一列,在本例中为first_name。这与在SQL中使用GROUP BY不同。

然后你可以循环它们

foreach($data as $first_name => $civ_array){
   ...
}

因此,在第一次迭代之上使用我的数据会给你这个

$first_name = 'bob'
$civ_array = [
       ['civ_licenses1'],
       ['civ_licenses2'],
 ];

答案 1 :(得分:0)

如果我理解正确,你的代码应该是这样的:

<?php
try {
    $conn = new PDO('mysql:host=localhost; dbname=driving','root','');
    $sel = "SELECT first_name, civ_licenses FROM users";
    $stmt = $conn->prepare($sel);
    $stmt->execute();
    $civArray = array();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

        $civArray[] = $row['civ_licenses'];
        if(in_array('`license_civ_driving`,1', $civArray)){
            echo $row['first_name'], 'has got the driving license';
        }

    }
    die;
} catch (PDOException $e) {
  echo "There was an error with your code!" . $e->getMessage();
  exit;
}
  1. 首先需要声明空数组

    $ civArray = array();

  2. 您可以使用fetch_style,如PDO :: FETCH_ASSOC http://php.net/manual/en/pdostatement.fetch.php

    $ stmt-&GT;取(PDO :: FETCH_ASSOC)

  3. 在每次迭代中向数组

    添加值

    $ civArray [] = $ row [&#39; civ_licenses&#39;];

  4. 并检查此数组中的许可证值

    if(in_array('`license_civ_driving`,1', $civArray)){
        echo $row['first_name'], 'has got the driving license';
    }