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

  1. The news.php script connects to the database and retrieves all news articles from the news_articles table.
  2. It then loops through the results and displays each article's title, description, and a link to read more.
  3. The article.php script connects to the database and retrieves the article with the specified ID.
  4. It then displays the article's title and content.

Note