-1

源代码:

<?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
              )
4

3 回答 3

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);

注意获取模式

于 2013-05-10T09:16:05.810 回答
0

您正在使用默认的 fetch 样式,即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);
于 2013-05-10T09:16:12.383 回答
0

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

$stmt->fetchAll(PDO::FETCH_ASSOC);
于 2013-05-10T09:16:55.980 回答