
Introduction
Displaying real-time data on a website is a common requirement, especially for news portals, blogs, and dashboards. In this guide, we will show you how to fetch news from SQL using JavaScript and display it dynamically on a webpage.
This approach allows you to retrieve news articles stored in MySQL, PostgreSQL, or any other SQL database and display them efficiently. It is perfect for developers, bloggers, and businesses that want to automate news feeds without relying on external APIs. Moreover, this method ensures complete control over data while optimizing performance.
Why Fetch News from SQL Using JavaScript?
✅ Full Control Over News Data – Unlike APIs, you own and manage the data.
✅ Better SEO & Performance – No dependency on third-party sources.
✅ Custom Filtering & Sorting – Fetch only relevant news based on categories.
✅ Monetization with AdSense – Place ads before and after news content.
This method provides significant advantages over external news APIs. By managing the data yourself, you can ensure better customization, avoid API limitations, and achieve improved site performance.
Step 1: Setting Up SQL for Fetching News
To fetch news from SQL using JavaScript, we need a structured database table. Use the following SQL query to create a table:
CREATE TABLE news (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
link VARCHAR(500) NOT NULL,
published_date DATETIME DEFAULT CURRENT_TIMESTAMP
);
Next, insert some sample news articles:
INSERT INTO news (title, link) VALUES
("Breaking News: AI Revolution", "https://example.com/ai-news"),
("Tech Update: JavaScript Trends 2025", "https://example.com/js-trends"),
("SQL Performance Optimization Tips", "https://example.com/sql-performance");
Step 2: Creating a PHP API to Fetch News from SQL
Since JavaScript cannot directly interact with SQL databases, we use PHP as a backend API to retrieve news from the database:
<?php
header("Content-Type: application/json");
$host = "localhost";
$user = "root";
$password = "";
$database = "news_db";
$conn = new mysqli($host, $user, $password, $database);
if ($conn->connect_error) {
die(json_encode(["error" => "Database connection failed"]));
}
$sql = "SELECT title, link FROM news ORDER BY published_date DESC LIMIT 5";
$result = $conn->query($sql);
$news = [];
while ($row = $result->fetch_assoc()) {
$news[] = $row;
}
$conn->close();
echo json_encode($news);
?>
Save this file as fetch_news.php
and upload it to your server. This script will act as the bridge between your SQL database and JavaScript.
Step 3: Using JavaScript to Fetch News from SQL
Now, let’s create a simple HTML page that will fetch news from SQL using JavaScript:
<div id="news">Loading latest news...</div>
<script>
async function fetchNews() {
try {
let response = await fetch('fetch_news.php');
let data = await response.json();
let newsContainer = document.getElementById("news");
newsContainer.innerHTML = "";
data.forEach(article => {
let newsItem = document.createElement("p");
newsItem.innerHTML = `<a href="${article.link}" target="_blank">${article.title}</a>`;
newsContainer.appendChild(newsItem);
});
} catch (error) {
console.error("Error fetching news:", error);
document.getElementById("news").innerHTML = "Failed to load news!";
}
}
fetchNews();
setInterval(fetchNews, 60000); // Refresh every 60 seconds
</script>
Step 4: Embedding in WordPress
- Go to WordPress Dashboard → Open the post editor.
- Click on ‘Custom HTML’ Block → Paste the JavaScript code above.
- Save & Publish → Your site will now display SQL-driven news!
Additionally, ensure that your WordPress hosting supports PHP scripts. If not, you may need to configure your settings or use a plugin.
Best AdSense Monetization Strategy
To maximize AdSense earnings, use strategic ad placements:
✔ Before the News Section – Ensures high visibility.
✔ After the News Section – Captures clicks post-reading.
✔ Sidebar Ads – Helps with additional revenue.
✔ Auto Ads – Let Google optimize placement dynamically.
Implementing these strategies will boost your AdSense revenue while keeping user experience smooth.
SEO Optimization Tips for Fetching News from SQL Using JavaScript
📌 Use Long-Tail Keywords: “Fetch news from SQL using JavaScript”, “SQL-powered news aggregator”, “Display MySQL news on website”.
📌 Include Internal & External Links:
- Internal Link: Join our SQL Community
- External Link: Official MySQL Documentation
📌 Write a Strong Meta Description (Example below).
📌 Optimize Images with Alt Text to boost search rankings.
📌 Improve Readability by breaking long sections into concise paragraphs.
Conclusion
Now you have a fully functional, SQL-driven news aggregator that works seamlessly with JavaScript. This solution is efficient, customizable, and monetizable with AdSense. Simply follow the steps, copy the code, and start earning today!