0

使用第一组代码我可以打印数组,但是第二段是为了将数组存储到变量中但是这没有任何建议?数组是空的?

 $stmt = $conn->prepare("SELECT admin_name FROM adminuser_tbl");
    if ($stmt->execute()) {
       while ($row = $stmt->fetch()) {
    print_r($row);
    }
  }

下面不工作

 $stmt = $conn->prepare("SELECT admin_name, adminuser_id FROM adminuser_tbl");
      if ($stmt->execute()) {
          $user_list = array();
     while ($row = $stmt->fetch()) { 
          $user_list[$row->adminuser_id] = $row->admin_name; 
     }
   }

如果我打印第一段的数组结果,它们都设置为 [0]???

Array ( [admin_name] => User1 [0] => User1 ) Array ( [admin_name] => User2 [0] => User2 ) Array ( [admin_name] => User3 [0] => User3 ) Array ( [admin_name] => User4 [0] => User4 ) 
4

1 回答 1

2

如果要将行作为对象提取,则需要设置提取模式。默认是PDO::FETCH_BOTH给你一个带有整数和命名键的数组。(查看您的 print_r 输出)

$stmt = $conn->prepare("SELECT admin_name, adminuser_id FROM adminuser_tbl");
if ($stmt->execute()) {
    $stmt->setFetchMode(PDO::FETCH_OBJ);
    $user_list = array();
    while ($row = $stmt->fetch()) {
        $user_list[$row->adminuser_id] = $row->admin_name;
    }
}

或者只使用 foreach 循环,因为 PDOStatement 实现了 Traversable 接口。

$stmt = $conn->prepare("SELECT admin_name, adminuser_id FROM adminuser_tbl");
if ($stmt->execute()) {
    $stmt->setFetchMode(PDO::FETCH_OBJ);
    $user_list = array();
    foreach ($stmt as $row) {
        $user_list[$row->adminuser_id] = $row->admin_name;
    }
}

对于其他获取模式,请看这里:pdo.constants

于 2013-08-01T12:14:24.070 回答