输出问题与pdo :: fetchall

时间:2013-05-10 09:14:15

标签: php pdo

源代码:

<?php
$dsn = 'mysql:dbname=oop;host=localhost;';
$user = 'admin';
$password = 'password';
try {
$pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
$stmt = $pdo->prepare("select * from be_users");
$stmt->execute();
echo "<pre>";
print_r($stmt->fetchAll());
echo "</pre>";
?>

结果:

Array
(
    [0] => Array
        (
            [username] => tom
            [0] => tom
            [email] => dsfde@gmail.com
            [1] => dsfde@gmail.com
        )

    [1] => Array
        (
            [username] => tom3
            [0] => tom3
            [email] => sdfsdfs@gmail.com
            [1] => sdfsdfs@gmail.com
        )
     ...

问题:

为什么结果不是这样的:

Array
(
    [0] => Array
        (
            [username] => tom
            [email] => dsfde@gmail.com
        )

    [1] => Array
        (
            [username] => tom3
            [email] => sdfsdfs@gmail.com
              )

3 个答案:

答案 0 :(得分:1)

$dsn = "mysql:host=localhost;dbname=oop;charset=utf8";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $password, $opt);

请注意提取模式

答案 1 :(得分:0)

您正在使用默认的提取样式,即PDO::FETCH_BOTH,这意味着您将获得一个数字和关联索引的数组。请改用PDO::FETCH_ASSOC

print_r($stmt->fetchAll(PDO::FETCH_ASSOC));

您可以在PDOStatement::fetchAll()

的手册页中找到有关抓取样式的更多信息

请注意,您可以为每个语句指定获取模式,也可以为每个PDO实例指定全局:

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

答案 2 :(得分:0)

您必须手动指定获取样式:

$stmt->fetchAll(PDO::FETCH_ASSOC);