0

我已经使用 foreach 循环来显示 myphp 数据库中的行,但是我现在想以 DESC 顺序显示它(首先显示最后一行)但是研究告诉我不要在数组中使用 SELECT 命令?还有其他方法吗?非常感谢。

索引.php:

<?php 
include("app/database/db.php");

$posts = selectAll('posts', ['published' => 1]);
?>


<?php foreach ($posts as $post): ?>

    <div class="post">
      <div class="col-lg-6">

      <!-- HEADLINE -->
      <h1><strong><a href="/single_page_main.php?id=<?php echo $post['id']; ?>"><?php echo $post['title']; ?></a></strong></h1>
      
      <!-- TEXT BODY -->
      <!-- <h4></?php echo $post['body']; ?></h4> displays the full body -->
      <h4 class="mainbody"><?php echo html_entity_decode(substr($post['body'], 0, 100) . '...'); ?></h4> 
      <!-- IMAGE -->
      <div class="col-lg-6">
        <img src="<?php echo '/assets/images/' , $post['image']; ?>" style="width: 550px; height:      350px; object-fit: cover;">
      </div>

    </div>

    <?php endforeach; ?> 

db.php 文件:

<?php

function selectAll($table, $conditions = []) {

  global $conn;
  $sql = "SELECT * FROM $table";
  if (empty($conditions)) {
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    return $records;
  } else {
    $i = 0;
    foreach ($conditions as $key => $value) {
      if ($i === 0) {
        $sql = $sql . " WHERE $key=?";
      } else {
        $sql = $sql . " AND $key=?";
      }
      $i++;
    }


    $stmt = executeQuery($sql, $conditions);
    $records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    return $records;
  }
}

?>
4

0 回答 0