【问题标题】:PHP combine 2 mysql tables without duplicatesPHP组合2个没有重复的mysql表
【发布时间】:2015-10-06 15:17:52
【问题描述】:

我有两个mysql表:

表 1(事件):

|event_id|club_id|date|time|title|description|type|

表 2(events_participants):

|id|event_id|name|img|

这就是我的 php 脚本获取表一(事件)的样子:

$sql = "SELECT * FROM events WHERE club_id='$club'";
$result = $conn->query($sql);

if ($result->num_rows > 0) { 

    $rows = [];       
    while($row = $result->fetch_assoc()) {
        // Add all rows to an array
        $rows[] = $row;
    }

    // Json encode the full array
    echo json_encode($rows);

} else {
    echo "0results";
}

例如上面的 php 代码产生以下结果:

[
    {
        "event_id": "123456",
        "club_id": "1234567890",
        "organizer": "name",
        "date": "2016-04-24",
        "time": "08:00",
        "title": "Test Event",
        "description": "test...",
        "type": "Ride"
    }
]

我怎样才能加入这两个表,使其看起来像这样,例如:

[
     {
           "event_id": "123456",
           "club_id": "1234567890",
           "organizer": "name",
           "date": "2016-04-24",
           "time": "08:00",
           "title": "Test Event",
           "description": "test...",
           "type": "Ride",
           "name": "yourname",
           "img": "imageurl"
      }
]

表 1 (events) 具有唯一的 event_id 行,表 2 (events_participants) 可以具有具有重复 event_id 的行。 因此,当表 2 中有重复项时,我正在寻找这样的结果:

 [
    {
        "event_id": "123456",
        "club_id": "1234567890",
        "organizer": "name",
        "date": "2016-04-24",
        "time": "08:00",
        "title": "Test Event",
        "description": "test...",
        "type": "Ride",
        "name": [
            "yourname",
            "yourname2"
        ],
        "img": [
            "imageurl",
            "imageurl2"
        ]
    }
]

【问题讨论】:

    标签: php mysql arrays join


    【解决方案1】:

    您无法在 SQL 中获得如下所示的结果集

        "name": [
            "yourname",
            "yourname2"
        ],
        "img": [
            "imageurl",
            "imageurl2"
        ]
    

    至少,不容易。您可以做的最接近的是:

    $mysqli->prepare("SELECT * FROM events e INNER JOIN events_participants ep ON e.event_id = ep.eventid WHERE club_id= ? ORDER BY event_id";
    $stmt -> bind_param("s", $club);
    

    这将为每个参与者提供一行,其中包含 events 表中的所有相关值。

    您应该使用支持变量绑定的方法访问数据库,例如mysqli 或PDO。

    【讨论】:

      猜你喜欢
      • 2013-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多