PHP - 使用它们的关系从表中回显数据

时间:2018-06-18 21:35:59

标签: php mysqli

美好的一天:)

我有2个表 - 一个包含主标题,另一个包含子标题和相关段落,它们与TitleID和LinkID上的外键相关,如下所示:

enter image description here

我的想法是创建一些包含主要标题的div - 来自sectionamain,其中包含来自sectiona的相关子内容,通过LinkID和TitleID链接。

initState

提前谢谢你 XX

1 个答案:

答案 0 :(得分:0)

要解决分组问题,需要在数组中创建数据结构。由于数据库将为行提供重复信息,因此请将此重复信息用作数组中的键。

<?php
function get_practices() {
    global $connection;

    // It's good practice to specify which fields you want to get from the database.
    // for clarity, I'm using heredoc format. 
    $query = >>>SECTIONAQUERY

SELECT am.TitleID, am.MainTitle, a.HeadingID, a.title, a.content  
FROM sectionamain am
LEFT JOIN sectiona a
ON a.HeadingID = am.TitleID 
ORDER BY sectionamain.TitleID ASC

SECTIONAQUERY;

    $A_list = mysqli_query($connection, $query);
    confirm_query($A_list);
    return $A_list;    
}

/**
 * group_items 
 *
 * takes database results and groups them by ID
 *
 * @param mysqli_result
 * @return array
 */
function group_items($db_results) {
  $data = array();
  while($row = mysqli_fetch_assoc($db_results)) {
    $title_id = htmlentities($row['TitleID']);

    // group Main Title by title id
    $data[$title_id]['title'] = htmlentities($row['MainTitle']);

    // group data by title id
    $data[$title_id]['data'][] = array(
      'HeadingID' => htmlentities($row['HeadingID']),
      'title'     => htmlentities($row['title']),
      'content'   => htmlentities($row['content'])
      );
  }

  return $data;
}

然后在你看来,你可能会有这样的事情:

<?php 
$A_list = get_practices();
$data = group_items($A_list);

// or, alternatively, $data = group_items(get_practices());

// now, go into "html mode" instead of in PHP, 
// using PHP only for looping and variable substitution:
?>
<html>
<head>
...
</head>
<body>
  <div>Your header stuff</div>
  <div class="info">
    <div class="wrap">
      <?php foreach($data as $row): ?>
        <h1 class="showcontent" id="<?= $row['title'] ?>"></h1>
        <?php foreach($row['data'] as $sub_row): ?>
          <h3><?= $sub_row['title'] ?></h3>
          <div class="content"><?= $sub_row['content'] ?></div>

          <!-- bonus: link to a new page? -->
          <div><a href="detail_page.php?id=<?= $sub_row['HeadingID'] ?>"><?= $sub_row['title'] ?></a></div>

        <?php endforeach; ?>
      <?php endforeach; ?>
    </div>
  </div>
</body>
</html>

注意,我个人不会将输出粘在一个函数中;这是混合逻辑和演示。通过使用PHP的内置模板,您不必担心转义引号。只需使用<?= ?>语法来删除PHP变量。使用include语句而不是调用该函数。 (或者,您可以始终将函数include视为局部视图。)

希望这能解决你的问题!