PHP-查询的单个结果

时间:2019-01-12 22:13:31

标签: php pdo

我正在尝试在表单中显示查询结果。我想查看TOTAL_PRICE,共CUSTOMERID = 3。

这是我的代码:

event.clientY

我的php表单显示结果1而不是50。

我认为它显示的是行数。

SQL运行正常。 PHP代码最终是错误的。

1 个答案:

答案 0 :(得分:2)

替换您的代码:

$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);$result = $stmt->fetch(PDO::FETCH_ASSOC);echo $result;由回波$result["total_price"];

setFetchMode设置默认的提取方式(http://php.net/manual/es/pdostatement.setfetchmode.php),但不从执行的语句中检索数据(必须使用fetch)

您的最终代码将是:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database_ps";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT (COALESCE(a.price, 0) - COALESCE(f.price, 0)) AS total_price FROM tblcustomer c LEFT JOIN (SELECT CustomerID, SUM(Price) as price FROM tblappointment GROUP BY CustomerID ) a ON a.CustomerID = c.CustomerID LEFT JOIN (SELECT CustomerID, SUM(Price) as price FROM tblfinances GROUP BY CustomerID ) f ON f.CustomerID = c.CustomerID where c.CustomerID=3"); 
    $stmt->execute();

    $result = $stmt->fetch(PDO::FETCH_ASSOC); 
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
echo $fetch["total_price"]; 

$conn = null;
?>