PHP - 显示更多文章功能反馈

Ale*_*yer 5 php mysql database forms performance

目前,我有一个文章页面,它读取我的数据库表中的所有文章,并在页面上打印每个文章,从最新的开始.

但是,我正在制作的系统将会使用很长时间(小公司的学生项目)并且会有很多文章.我不希望用户和服务器必须在网页上一次加载所有文章.我有想法如何做到这一点,但我想先由其他人运行这个想法.

从概念上讲,我正在考虑做的是在页面上加载一些文章.在底部,会有一个"显示更多"按钮或链接,可以从数据库中读取和显示更多文章(希望无需重新加载页面,但我非常怀疑它是否可行).

实际上,它可能会是这样的:使用表单,在隐藏字段中存储显示文章的数量,提交"显示更多"重新加载页面并使用$ _POST和while循环显示存储的数字+更多文章.这是下面的简化示例.

<form method="post" action="articlePage.php">
   <?php
   if(isset($_POST["articleCount"])){
      $articleCount = $_POST["articleCount"] + 5;
   }
   else{
      $articleCount = 5
   }

   //Assuming we open the connect, execute the query and then close the connection
   $count = 0;
   while($result = mysqli_fetch_array($selectNews) && $count <= $articleCount){
      echo $result["articleName"] . "<br/>";
      count = count + 1;
   }

   echo "<input type='hidden' value='" . $articleCount . '" name='articleCount'/>";
   ?>
   <input type="submit" value="Show more"/>
</form>
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  • 是否有更有效/更好的方法来解决这个问题?
  • 有没有办法我不必重新加载页面?

任何提示或信息都非常感谢!我在提问时有点新意,所以如果有任何遗漏,请告诉我

Mr.*_*ato 3

您可以将 PHP 代码放在单独的文件中并使用 AJAX 调用它。你可以这样做:

function getArticleCount(){
   if(isset($_POST["articleCount"])){
      $articleCount = $_POST["articleCount"] + 5;
   }
   else{
      $articleCount = 5
   }

   //Assuming we open the connect, execute the query and then close the connection
   $count = 0;
   while($result = mysqli_fetch_array($selectNews) && $count <= $articleCount){
      echo $result["articleName"] . "<br/>";
      count = count + 1;
   }

   echo "<input type='hidden' value='" . $articleCount . '" name='articleCount'/>";
}

getArticleCount();
Run Code Online (Sandbox Code Playgroud)

下面是一个AJAX和PHP结合使用的例子,让你感受一下。