为什么PDOStatement在单次提取时返回false?

时间:2014-03-28 07:00:55

标签: php mysql pdo mariadb

当我尝试通过获取单行来执行SELECT查询时,我不知道为什么PHP总是返回false。

我的表是:

create table profile
(
    id int not null auto_increment,
    email char(50) not null,
    password char(100) not null,
    name char(100) not null,
    surname char(50) not null,
    street char(50) not null,
    homeno char(5) not null,
    postalcode char(5),
    homearea char(100) not null,
    group_id int not null,
    primary key(id)
);
create table usergroups
(
    id int auto_increment not null,
    name char(30) not null,
    primary key(id)
);

我有一些数据集,然后我尝试用它们来读取它们(用于获取一个用户配置文件;简化示例):

$sSQL = <<<SQL
SELECT `profile`.`id` AS `profile.id`, `profile`.`email` AS `profile.email`, `profile`.`password` AS `profile.password`, `profile`.`name` AS `profile.name`, `profile`.`surname` AS `profile.surname`, `profile`.`street` AS `profile.street`, `profile`.`homeno` AS `profile.homeno`, `profile`.`postalcode` AS `profile.postalcode`
FROM `profile`
inner join `usergroups` on `profile`.`group_id` = `usergroups`.`id`
WHERE `profile`.`email` = ?
SQL;
$pdo = new PDO($sDsn, $sUser, $sPass);
$stmt = $pdo->prepare($sSQL);
$sEmail = 'some@example.com';
$stmt->bindValue(1, $sEmail, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch();
var_dump($result);

我的数据库是MariaDB。

同样的查询之前没有问号,所以之前没有任何东西要绑定。我猜数据库和/或PHP存在错误。

1 个答案:

答案 0 :(得分:1)

编程不像小说文学。每个前提都必须经过验证。

$pdo = new PDO($sDsn, $sUser, $sPass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sSQL = SELECT p.* FROM profile inner join usergroups u on group_id = u.id 
        WHERE email = 'some@example.com';
$user = $pdo->query($sSQL)->fetch();
var_dump($user);

$sSQL = SELECT p.* FROM profile inner join usergroups u on group_id = u.id 
        WHERE email = ?;
$stmt = $pdo->prepare($sSQL);
$stmt->execute(['some@example.com']);
$user = $stmt->fetch();
var_dump($user);

运行此代码并在此处粘贴结果。或者自己考虑一下