我尝试在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)
时,我总是得到
布尔(假)
结果。
我的想法是否存在别名或其他错误的问题?
答案 0 :(得分:4)
你需要在fetch()之前执行()。
$statement = $pdo->prepare($query);
$statement->execute();
$retValue = $statement->fetch(PDO::FETCH_ASSOC);
请阅读documentation中的代码示例。