How can PHP be used to retrieve data from a MySQL database for a news system?
To retrieve data from a MySQL database for a news system using PHP, you can establish a connection to the database, write a SQL query to select the desired data, execute the query, and then fetch the results to display on the website.
<?php
// Establish connection to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "news_system";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Write SQL query to retrieve news data
$sql = "SELECT id, title, content FROM news";
// Execute the query
$result = $conn->query($sql);
// Fetch and display the results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Title: " . $row["title"]. " - Content: " . $row["content"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>
Keywords
Related Questions
- How can JPgraph be effectively integrated and utilized with PDO in PHP for data visualization?
- What are some recommended resources or tutorials for effectively linking images in TCPDF using PHP?
- What potential security vulnerabilities are present in the PHP script provided for file upload with database entry?