PHP - Show more articles

I currently have an article page that reads all the articles in my database table and prints each on the page, starting with the most recent.

However, the system that I create will be used for a long time (student project for a small company), and there will be many articles. I don’t want the user or server to have to download all the articles on the web page at once. I have ideas on how to do this, but at first I wanted to start the idea with other people.

Conceptually, I thought it was loading several articles per page. At the bottom there will be a "Show more" button or a link that will read and display a few more articles from the database (I hope without reloading the page, but I very much doubt that this can work).

In practice, it probably will look something like this: use the form, store the number of articles displayed in a hidden field, send β€œShow more” to reload the page and use the $ _POST and while loop to display the saved number + a few more articles. Here is a simplified example.

<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> 

My questions:

  • Is there a more efficient / better way to do this?
  • Is there a way when I do not need to reload the page?

Any tips or pieces of information are greatly appreciated! I'm a little new to asking questions, so if something is missing let me know

+5
source share
1 answer

You can put your PHP code in a separate file and invoke it using AJAX. You can do something like this:

 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(); 

The following is an example of using AJAX and PHP to make you feel it.

+3
source

Source: https://habr.com/ru/post/1209286/


All Articles