Php news script
Here is a basic PHP script for a news website:
news.php
<?php
// Database connection settings
$db_host = 'localhost';
$db_username = 'root';
$db_password = '';
$db_name = 'news';
// Create connection
$conn = new mysqli($db_host, $db_username, $db_password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}
// Get all news articles
$sql = "SELECT * FROM news_articles";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<h2>". $row["title"]. "</h2>";
echo "<p>". $row["description"]. "</p>";
echo "<p><a href='article.php?id=". $row["id"]. "'>Read more</a></p>";
}
} else {
echo "No news articles found";
}
// Close connection
$conn->close();
?>
article.php
<?php
// Database connection settings
$db_host = 'localhost';
$db_username = 'root';
$db_password = '';
$db_name = 'news';
// Create connection
$conn = new mysqli($db_host, $db_username, $db_password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}
// Get article by ID
$id = $_GET['id'];
$sql = "SELECT * FROM news_articles WHERE id = '$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<h2>". $row["title"]. "</h2>";
echo "<p>". $row["content"]. "</p>";
}
} else {
echo "Article not found";
}
// Close connection
$conn->close();
?>
news_articles table structure
CREATE TABLE news_articles (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
description TEXT,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
How it works
- The
news.php
script connects to the database and retrieves all news articles from thenews_articles
table. - It then loops through the results and displays each article's title, description, and a link to read more.
- The
article.php
script connects to the database and retrieves the article with the specified ID. - It then displays the article's title and content.
Note
- This is a very basic script and you should consider adding security measures such as validating user input and using prepared statements to prevent SQL injection.
- You should also consider adding more features such as user authentication, commenting, and categorization.
- This script assumes that you have a
news_articles
table with the specified columns. You will need to create this table in your database before running the script.