从 fetchAll pdo 获取字符串数组



我面临着一些非常奇怪的事情,不明白为什么我会得到下一个结果,我有 2 个文件,索引.php和发送.php发送.php从数据库的用户和索引列表中获取.php将列表显示为表格,在索引中.php我正在使用需要发送.php,在发送中.php我有这段代码

    $sth->setFetchMode(PDO::FETCH_ASSOC);
    $sth->execute();
    $result = $sth->fetchAll();
    echo '<pre>';
    print_r($result);

它工作得很好,但在索引中.php

    <?php if (isset($result)): ?>
        <pre>
            <?php print_($result); ?>
        </pre>
    <?php endif; ?>

我得到这样的数组 [0] => 数组

为什么?

应该很明显,不像fetch()迭代每一行fetchAll()返回一个行列表,每个行都在数组的单独索引中。

$result[0]['column'];
        ^
        |-- first result.

所以你应该这样做:

foreach($result as $row){
  echo $row['colname'];
}

这将使$row默认为数组,其中键是列名。


附带说明一下,如果要检查是否有结果,请执行以下操作:

// this:
if($result){}
// equals:
if(!empty($result)){}

使用 isset() 将导致意外行为:

if(isset($result = false)){
  // query failed, but this code still executes.
}

此外,尝试访问另一个脚本中定义的全局变量也是不好的做法,请避免这样做。改为将代码包装在一个小函数中:

function dbGetUsers(){
  // connect to db or whatnot.
  $sth = $pdo->prepare('....');
  if($sth->execute()){
    return $sth->fetchAll();
  } else {
    die('query failed '. __FILE__ . __LINE__ - 2);
  }
}

最新更新