簡體   English   中英

PHP-查詢的單個結果

[英]PHP - single result of a query

我正在嘗試在表單中顯示查詢的結果。 我想查看TOTAL_PRICE,共CUSTOMERID = 3。

這是我的代碼:

<?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->setFetchMode(PDO::FETCH_ASSOC); 
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
echo $result; 

$conn = null;
?>

我的PHP表單顯示為結果1而不是50。

我認為它顯示的是行數。

SQL工作正常。 PHP代碼最終是錯誤的。

替換您的in代碼:

$result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 通過$result = $stmt->fetch(PDO::FETCH_ASSOC); echo $result; 通過echo $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;
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM