PDO fetchall查询,显示多个结果,但每个ID只有1个

时间:2016-10-06 09:05:11

标签: php pdo

我的问题不明确所以我正在编辑。

我有一个网站,人们可以在这些网站上对其进行出价,在他们的帐户页面上,他们可以跟踪出价。但如果一个人在产品上出价两次,他们会看到该产品两次。所以我只希望每个产品的出价最高。

这是我的疑问:

$objDatabaseAds->prepare('SELECT * FROM bieden WHERE ownerid = :ownerid ORDER BY prijs DESC');

问候,

的Bram

修改

$objGetHighest = $objDatabaseAds->prepare('SELECT * FROM bieden WHERE ownerid = :ownerid GROUP BY adid');
$objGetHighest->bindParam('ownerid', $member_id);
$objGetHighest->execute();
$objGetHighestFetch = $objGetHighest->fetchAll(PDO::FETCH_ASSOC);

foreach ($objGetHighestFetch as $key) {
  $adID = $key['adid'];
  //This echoes 3 values which is good!!

  $objGetBid = $objDatabaseAds->prepare('SELECT * FROM bieden WHERE adid = :adid');
  $objGetBid->bindParam('adid', $adID);
  $objGetBid->execute();
  $objGetBidFetch = $objGetBid->fetchAll(PDO::FETCH_ASSOC);
}

所以这就是我现在所得到的。 $ adID回应了4个广告中的3个值,其中2个广告具有相同的ID,因此这很好。但后来我又做了另一个查询,然后我就看到了他一次显示的ID的出价。

Table

2 个答案:

答案 0 :(得分:2)

如果想要获得更高的一行,你可以试试这个,希望对你有帮助。干杯!

$query = $objDatabaseAds->prepare('SELECT * FROM bieden WHERE ownerid = :ownerid ORDER BY prijs DESC LIMIT 1');

$query->execute();

while($data = $query->fetch(PDO::FETCH_ASSOC)){
     echo $data['column_name'];
     echo $data['ownerid'];
}

答案 1 :(得分:2)

试试这个。只需添加GROUP BY adid,它就像你想要的那样工作。干杯!希望有帮助。

$objGetHighest = $conn->prepare("SELECT * FROM tabs WHERE ownerid = :ownerid GROUP BY adid");
$objGetHighest->bindParam('ownerid', $member_id);
$objGetHighest->execute();
$objGetHighestFetch = $objGetHighest->fetchAll(PDO::FETCH_ASSOC);

foreach ($objGetHighestFetch as $key) {
  $adID = $key['adid'];
  //This echoes 3 values which is good!!
  //echo $adID."<br />";

  $objGetBid = $conn->prepare("SELECT * FROM tabs WHERE adid = '$adID' GROUP BY adid ");
  $objGetBid->execute();
  $objGetBidFetch = $objGetBid->fetchAll(PDO::FETCH_ASSOC);
  print_r($objGetBidFetch);
}