我有这个代码它工作正常,但我想将代码更改为另一个结构

时间:2016-11-15 00:40:17

标签: php mysql join

这是我目前运作良好的代码:

  <?php
    $sql = "SELECT * FROM te_events order by eventTitle ASC ";
    $result = $conn->query($sql);

    while($row = $result->fetch_assoc()) 
    {
        $venueID = $row['venueID'];
        $catID = $row['catID'];

        $sql2 = "SELECT * FROM te_venue where venueID='$venueID'";
        $result2 = $conn->query($sql2);

        while($row2 = $result2->fetch_assoc()) 
        {
            $venueName = $row2['venueName'];
        }

        $sql3 = "SELECT * FROM te_category where catID='$catID'";
        $result3 = $conn->query($sql3);

        while($row3 = $result3->fetch_assoc()) 
        {
            $catName = $row3['catDesc'];
        }

?>

但我想将其更改为此格式。我只能做到这一点不能超过这个我得到错误。

<?php
    $sql ="SELECT eventTitle, eventID, venueID, catID, eventStartDate, eventEndDate, eventPrice FROM te_events ORDER BY eventTitle ASC";
    $queryresult = mysqli_query($conn, $sql) or die(mysqli_error($conn));
    while ($row = mysqli_fetch_array($queryresult)) {

        $venueID = $row['venueID'];
        $catID = $row['catID'];
        $venueName = $row['venueName'];
        $catName = $row['catDesc'];

?>

那我怎么能这样做呢? 我如何加入两张桌子?

1 个答案:

答案 0 :(得分:0)

您应该能够join其他2个表来获取所需的列。

SELECT e.eventTitle, e.eventID, e.venueID, e.catID, e.eventStartDate, e.eventEndDate, e.eventPrice, v.venueName, c.catDesc
 FROM te_events as e
join te_venue as v
on e.venueID = v.venueID
join te_category as c
on c.catID = e.catID
ORDER BY eventTitle ASC

您还应该避免将数据直接放入查询中。如果您需要这样做,请使用参数化查询。这就是SQL注入(或第二级)的发生方式。