【问题标题】:Why does the PDOStatement return false on single fetch?为什么 PDOStatement 在单次提取时返回 false?
【发布时间】:2014-05-07 12:37:42
【问题描述】:

当我尝试通过获取单行执行 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 有错误。

【问题讨论】:

  • 您是否尝试过回显$sSQL 的值?然后,您可以直接在 phpMyAdmin 或类似工具中运行它,以确认查询本身是有效的。
  • 是的。正如我上面写的,查询没有问号,所以我的意思是使用固定字符串 e。 G。比如 ``profile.email` = 'some@example.com'`。

标签: php mysql pdo mariadb


【解决方案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);

运行此代码并将结果粘贴到此处。还是自己考虑吧

【讨论】:

  • 好的,谢谢。在我较大的班级中,我曾经获取一个不存在的列。我刚刚删除了它,一切正常。谢谢你的帮助。以后我会一直打开 PDO 的异常抛出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-19
  • 2018-10-29
  • 2013-09-18
  • 1970-01-01
  • 2011-05-22
  • 2014-11-17
  • 2014-03-11
相关资源
最近更新 更多