What are some methods for creating a news ticker using PHP and MySQL?
To create a news ticker using PHP and MySQL, you can fetch news articles from a MySQL database and display them in a scrolling ticker format on a webpage. You can achieve this by querying the database for the latest news articles, storing them in an array, and then using JavaScript to create a scrolling effect on the webpage.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "news_database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query database for latest news articles
$sql = "SELECT * FROM news ORDER BY date DESC LIMIT 5";
$result = $conn->query($sql);
// Store news articles in an array
$news = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$news[] = $row['headline'];
}
}
// Close database connection
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>News Ticker</title>
<style>
.ticker {
width: 100%;
overflow: hidden;
}
.ticker ul {
list-style-type: none;
padding: 0;
margin: 0;
white-space: nowrap;
animation: ticker 10s linear infinite;
}
.ticker li {
display: inline;
padding: 0 20px;
}
@keyframes ticker {
0% {
transform: translateX(100%);
}
100% {
transform: translateX(-100%);
}
}
</style>
</head>
<body>
<div class="ticker">
<ul>
<?php foreach($news as $article): ?>
<li><?php echo $article; ?></li>
<?php endforeach; ?>
</ul>
</div>
</body>
</html>
Keywords
Related Questions
- Why is it recommended to avoid using $HTTP_USER_AGENT in PHP scripts and what alternative approach can be taken?
- How can setting a UNIQUE constraint in a database table help prevent duplicate entries when inserting data from a form in PHP?
- How can PHP be used to set a checkbox as checked when a specific condition is met?