【问题标题】:I have got this code it is working fine but I want to change the having code into another structure我有这个代码,它工作正常,但我想将有代码更改为另一个结构
【发布时间】:2016-11-15 00:40:16
【问题描述】:

这是我目前工作正常的代码:

  <?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'];

?>

那我该怎么做呢?
如何连接两个表?

【问题讨论】:

  • 那我该怎么做呢?
  • 如何连接两个表?
  • 没有代码的问题对未来的访问者没有意义。请保留问题中的代码。如果有一些安全数据(我没有看到),你应该在你的服务器上重置它,因为它已经暴露了。

标签: php mysql join


【解决方案1】:

您应该能够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 注入(或第二级)发生的方式。

【讨论】:

  • 发生了什么?可能还需要在order by 中为eventTitle 提供别名,这是唯一的名称吗?
  • 哦,我使用了错误的别名。你知道这段代码在做什么吗?在插入之前,您应该真正了解一些内容。evc 是您的表的别名。
  • 我还是不明白对不起:(
  • 我已经更新了答案,看看。 te_events as e 使所有 e. 引用 te_events 表。如果这些列不在该表中,请更正它们,与其他 c.v. 相同。
  • 太棒了,我刚刚复制并粘贴了代码,一切都正确了,我怎么能避免为此进行 SQL 注入。
猜你喜欢
  • 1970-01-01
  • 2020-01-20
  • 2020-08-27
  • 2018-06-02
  • 1970-01-01
  • 2012-03-26
  • 2019-11-12
  • 1970-01-01
  • 2018-01-26
相关资源
最近更新 更多