如何在 PHP 中从数据库不同的表中获取特定和唯一的数据


how to fetch specific and unique data from database different tables in php

我想从数据库中获取数据 三个表都链接在一起。我遇到了问题,我已经尝试了很多方法,比如merge, unique and separate list.以下是代码。

<?php
$conn=new mysqli("localhost","root","","db");
$rows=$conn->query("select Account,Amount, event_name,event_description from donations
                    LEFT JOIN accounts
                    ON accounts.ID_Account=donations.ID_Account
                    LEFT JOIN events
                    ON events.event_id=donations.event_id ");
$rows1=$conn->query("SELECT Account from accounts");
while((list($Account, $Amount, $event_name,$event_description)=$rows->fetch_row()) and (list($Account)=$rows1->fetch_row()))
{   
echo "<tr><td> $Account</td><td> $Amount </td><td>$event_name</td><td>$event_description</td></tr>";    
}   
?>

现在的问题是,它显示了来自帐户的重复数据,我也希望它就像如果帐户没有捐赠$Amount一样,$Account它不应该在Account面前显示捐赠,但它正在显示。 有什么方法可以让它按照我想要的方式工作吗?非常感谢。

您正在寻找一些数据水化方法。现在,您将获得带有结果数据的A * B * C = X行,因为您正在执行多个连接,并且来自mysql的结果数组将始终只有一个维度,因此会有很多重复的数据。

你想要的是具有多个维度的数组(或对象)。我假设你想要一个结果数组,如下所示:

$result = array(
    'account1' => array('event1', 'event2'),
    'account1' => array('event3', 'event4', 'event5')
);

对此有多种解决方案:

  1. 编写自己的数据水化方法,以使用结果中的值创建新数组
  2. 使用 JOIN 执行三个单个查询而不是一个查询,然后合并结果(甚至可以更快!
  3. 使用原则(一个php数据库抽象层),它可以完全按照你想要的去做,而不会有太多麻烦。

如果您开始编写新应用程序,我会推荐 3.)给你:

http://doctrine-orm.readthedocs.org/en/latest/tutorials/getting-started.html