[英]PHP - single result of a query
I am trying to show the result of a query in my form. 我正在尝试在表单中显示查询的结果。 I want to see the TOTAL_PRICE of CUSTOMERID=3.
我想查看TOTAL_PRICE,共CUSTOMERID = 3。
Here is my code: 这是我的代码:
<?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;
?>
my php form is showing as a result 1 instead of 50. 我的PHP表单显示为结果1而不是50。
I think it is showing the number of row. 我认为它显示的是行数。
The SQL is working fine. SQL工作正常。 The PHP code is wrong in the end.
PHP代码最终是错误的。
Replace your in code: 替换您的in代码:
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
by $result = $stmt->fetch(PDO::FETCH_ASSOC);
通过
$result = $stmt->fetch(PDO::FETCH_ASSOC);
and echo $result;
并
echo $result;
by echo $result["total_price"];
通过echo
$result["total_price"];
setFetchMode sets the default way of fetch ( http://php.net/manual/es/pdostatement.setfetchmode.php ), but does not retrieve data from executed statement (must use fetch) setFetchMode设置默认的获取方式( http://php.net/manual/es/pdostatement.setfetchmode.php ),但不从执行的语句中检索数据(必须使用fetch)
Your final code will be: 您的最终代码将是:
<?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.