PHP结合了2个没有重复的mysql表

时间:2015-10-06 15:17:52

标签: php mysql arrays join

我有两个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(事件)具有唯一的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"
        ]
    }
]

1 个答案:

答案 0 :(得分:0)

您无法在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表中的所有相关值。

您应该使用方法来访问支持变量绑定的数据库,例如mysqliPDO