我有一段威士忌数据库,销售价格在一段时间内。在我的数据库中,我有Name,Price Url和Id。
我有很多同名的威士忌,但促销价格不同。目前,当有人进行搜索时,会将他们带到显示他们搜索过的产品的搜索结果页面。
我想要做的是当有人点击链接查看完整的详细信息时,我希望能够显示该名称下所有威士忌的平均价格,但我很难看到。它的ressult.php我遇到的问题是我得到的回应是£。我似乎已经失去了名字和网址被回应 并没有得到名称url_img或平均价格(我试图计算。但我的重点是得到平均价格显示。
的search.php
$stmt = $conn->prepare("SELECT * FROM test_db WHERE name LIKE :name ORDER BY name ASC"); // Use = instead of LIKE for full matching
$stmt->bindParam(':name', $search);
$stmt->execute();
$count = $stmt->rowCount(); // Added to count no. of results returned
if ($count >= 1) { // Only displays results if $count is 1 or more
echo "<div class='results_found'>";
echo $count;
echo " results found<br>";
echo "</div>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<div class='results'>";
echo "<div class='result_name'>";
echo "<b>Whisky Name:</b><br>";
echo "<a href='details1.php?id={$row['lot_id']}' >{$row['name']}</a>";
echo "</div>";
echo "</div>";
}
} else {
echo " Sorry no records were found";
}
?>
**results.php**
<?php
$page='details';
include('header.php');
include ('navbar.php');
include ('connect.php');
if (isset($_GET['id'])) {
$sql = "SELECT name , AVG(price) , url_img , price FROM test_db JOIN (SELECT name, AVG(price) as avprice FROM test_db GROUP BY name) avcalc USING (name)
WHERE lot_id = :id";
$stmt = $conn->prepare($sql);
$stmt->execute( [ 'id' => $_GET['id'] ] );
$row = $stmt->fetch();
echo $row['name'];
echo '<br>';
echo '£';
echo $row['price'];
echo '<br>';
echo "<img src='".$row ['url_img']."' /><br />";
echo $row['avg'];
}
?>
答案 0 :(得分:1)
我认为你正在寻找这个:
SELECT `name`, AVG(price) as avg_price FROM `whisky` GROUP BY `name`
原始表数据:
此问题的结果:
如果您只需要一个价格,则可以针对 WHERE name = whisky
Avg现在位于:$ row [&#39; avg_price&#39;]
答案 1 :(得分:0)
您已经应用了加入查询,但您获得了AVG(价格),而不是 avgprice ,它出现在第一个表 test_db 中。 您需要创建另一个 test_db 的别名。 改变这一行
$sql = "SELECT name , AVG(price) , url_img , avprice FROM test_db JOIN (SELECT name, AVG(price) as avprice FROM test_db GROUP BY name) avcalc USING (name) WHERE lot_id = :id";
到此
$sql = "SELECT name , avcalc.avgprice , url_img , avprice FROM test_db JOIN (SELECT name, AVG(price) as avprice FROM test_db GROUP BY name) avcalc USING (name) WHERE lot_id = :id";
答案 2 :(得分:0)
知道了,
if (isset($_GET['id'])) {
$sql = "SELECT name
, price
, url_img
, avprice
FROM test_db
JOIN (
SELECT name
, AVG(price) as avprice
FROM test_db
GROUP BY name
) avcalc USING (name)
WHERE lot_id = :id";
$stmt = $conn->prepare($sql);
$stmt->execute( [ 'id' => $_GET['id'] ] );
$row = $stmt->fetch();
echo "{$row['name']}<br>
£{$row['price']}<br>
<img src='{$row['url_img']}'/><br>
{$row['avprice']}";