There is a database with some news. I need to list, for example, the last 5.

I have no problems with a query to the database, but I cannot process the information received. For example, let there be a news table with 3 lines: id, title, description.

What should be the PHP code to display 5 news on one page?

  • 2
    Take any example of working with a database from php, they are at every turn. there just cycles according to the data. So you make a loop for yourself while the database returns the data and form the html blocks for the news in it - Mike
  • I have lessons - just on this topic, a video, Avtar Dmitry Vallak - absolutely brilliantly simply explains, I am not a genius in php but with his lessons I have already written a template page and brought up articles from the base and already know how to edit them, and most importantly these There are lessons on youtube, look at them, you will not regret - user33274

2 answers 2

To display information on the page, you must use templates.

In the most primitive case, a template can be a separate PHP file, which is responsible for displaying all the information. Accordingly, we transfer the data obtained from the database to the template.

Accordingly, we need to get the data, and then connect our template file:

$data = $pdo->query("SELECT * FROM news ORDER BY id DESC LIMIT 5"); include 'news.php'; 

where in news.php already and will be output

 <div> <? foreach ($data as $row): ?> <div> <h3><?=$row['title']?></h3> <div><?=$row['description']?></div> </div> <? endforeach ?> </div> 
  • Thanks for the answer. I used mysql_connect and mysql_select_db to connect to the database. If I insert your code, I get the fatal error "Call to a member function mysqli_query () on a non-object". - n000000b
  • You cannot use mysql_connect and mysql_select_db. mysqli_query () is undesirable. It is necessary to read about PDO and use only it. - Ipatiev

In fact, there are many options for processing information from a database. I advise you to just read something like php + sql. A lot of information and examples of data processing obtained from the database. From my own experience I will say that it depends on what you need in the end. I personally presented the data from the database as a list and output

  • data
without any problems, but here some difficulties arose with php code. I advise you to climb on the tutorials such as the interaction of php and sql and there will be a lot that will help you, I assure you, at least it helped me.

  • Do not write an answer if you have absolutely nothing to say. - Ipatiev