【问题标题】:Running PDO Statement in PHP returns bool(false)在 PHP 中运行 PDO 语句返回 bool(false)
【发布时间】:2017-12-07 04:56:09
【问题描述】:

我尝试使用 php 中的此 SQL 查询获取计算值:$sql = "SELECT SUM(amount) as IncomeSum FROM income WHERE year = " . $year;

我尝试在此函数中使用 PDO 获取结果:

function getDatafromDB($query, $columnName){
    require 'db.php';

    try {
        $pdo = new PDO("mysql:host=localhost;dbname=$db_name", $db_user, $db_pass);

        $statement = $pdo->prepare($query);
        $retValue = $statement->fetch(PDO::FETCH_ASSOC);
        var_dump($retValue);

        return $retValue[$columnName];
    } catch (PDOException $e) {
        $error = "Error!: " . $e->getMessage() . "<br/>";

        return $error;
        die();
    }
}

我这样调用函数:

$sql = "SELECT SUM(amount) as IncomeSum FROM income WHERE year = " . $year;

$retValue = getDatafromDB($sql, "IncomeSum");

但是当我在上面的函数中var_dump($retValue) 时,我总是得到

布尔(假)

结果。

是别名有问题还是我的想法有什么问题?

【问题讨论】:

  • 你有没有想过execute()ing 准备好的查询?
  • @AbraCadaver 你的意思是execute()而不是fetch()
  • 不...准备,执行然后获取。查看示例php.net/manual/en/pdostatement.fetch.php

标签: php pdo


【解决方案1】:

在 fetch() 之前需要先执行()。

$statement = $pdo->prepare($query);
$statement->execute();
$retValue = $statement->fetch(PDO::FETCH_ASSOC);

请阅读documentation中的代码示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-13
    • 2021-07-06
    • 2011-09-19
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 2015-12-21
    相关资源
    最近更新 更多