How to make news on php

"Learn how to create a news system in PHP with an example code, to help you get started on your website!"

Creating a News Page in PHP

Creating a news page using PHP is a relatively simple task. In this tutorial, we will be creating a news page that will display the latest news from a MySQL database. This page will parse through the database and display the latest news items in a neat and organized way. Let’s get started.

The Database

First, we need to create a database to store our news. We will use the following MySQL command to create a database called “news”:

CREATE DATABASE news;

Next, we need to create a table to store our news items. We will use the following MySQL command to create a table called “news_items”:

CREATE TABLE news_items (
	id INT AUTO_INCREMENT PRIMARY KEY, 
	title VARCHAR(255) NOT NULL, 
	body TEXT, 
	date DATETIME
);

Now we can insert some news items into our table. We will use the following MySQL command to insert a news item into our table:

INSERT INTO news_items (title, body, date) 
VALUES ('Example News Title', 'Example News Body', '2020-01-01 00:00:00');

The PHP Code

Now that we have our database setup, we can start writing the PHP code to display our news. We will start by connecting to the database and retrieving the news items. We will use the following PHP code to connect to the database and retrieve the news items:

$db = new mysqli('localhost', 'username', 'password', 'news');
$sql = "SELECT * FROM news_items ORDER BY date DESC";
$result = $db->query($sql);

Now that we have our news items, we can start displaying them on the page. We will use the following PHP code to loop through the results and display the news items:

while($row = $result->fetch_assoc()) {
	echo '<h2>'.$row['title'].'</h2>';
	echo '<p>'.$row['body'].'</p>';
	echo '<p><em>'.$row['date'].'</em></p>';
}

Now, when the page is loaded, the latest news items will be displayed in a neat and organized way. We have now successfully created a news page using PHP.

Answers (0)