How to display news from database in php
To display news from a database in PHP, you'll need to follow these general steps:
- Connect to the database: Use a PHP extension like
mysqli
orPDO
to connect to your database. You'll need to provide the database host, username, password, and database name. - Query the database: Use a SQL query to retrieve the news articles from the database. You can use a
SELECT
statement to retrieve the data you need. - Fetch the results: Use a loop to fetch the results of the query and store them in a PHP array or object.
- Display the news: Use PHP to display the news articles on your website. You can use HTML, CSS, and JavaScript to format the output.
Here's an example of how you might do this using mysqli
:
<?php
// Connect to the database
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name');
// Check connection
if ($mysqli->connect_error) {
die('Connect Error: '. $mysqli->connect_error);
}
// Query the database
$query = "SELECT * FROM news_articles";
$result = $mysqli->query($query);
// Fetch the results
while ($row = $result->fetch_assoc()) {
$news_articles[] = $row;
}
// Display the news
foreach ($news_articles as $article) {
echo '<h2>'. $article['title']. '</h2>';
echo '<p>'. $article['content']. '</p>';
echo '<p>Published: '. $article['published_date']. '</p>';
echo '<hr>';
}
This code connects to a database, queries the news_articles
table, fetches the results, and then displays the news articles using a foreach
loop.
You can also use PDO
to connect to the database and query the data:
<?php
// Connect to the database
$dsn = 'mysql:host=localhost;dbname=database_name';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: '. $e->getMessage();
}
// Query the database
$query = "SELECT * FROM news_articles";
$stmt = $pdo->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Display the news
foreach ($result as $article) {
echo '<h2>'. $article['title']. '</h2>';
echo '<p>'. $article['content']. '</p>';
echo '<p>Published: '. $article['published_date']. '</p>';
echo '<hr>';
}
This code uses a PDO
object to connect to the database, prepare a query, execute the query, and then fetch the results. The rest of the code is similar to the mysqli
example.
Remember to replace the placeholders (localhost
, username
, password
, database_name
) with your actual database credentials and database name.