Home > Article > Backend Development > How to click a link to view news in php
With the development of Internet technology, how to achieve more convenient and faster news browsing has become a common challenge for many website developers. As a back-end language widely used in website development, PHP can implement many interesting functions, one of which is to click on a link to view news. This article will introduce how to use PHP to implement this function and introduce related technical points.
CREATE TABLE news (
id INT(11) NOT NULL AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
pub_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
The table contains four fields: id, title, content, pub_date. Among them, id is a self-increasing primary key, title stores the news title, content stores the specific content of the news, and pub_date stores the release time.
$conn = mysqli_connect($host, $user, $pwd, $db);
$sql = "SELECT * FROM news WHERE id = '{$id}'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
mysqli_free_result ($result);
mysqli_close($conn);
In the above code, $host, $user, $pwd, $db are the parameters required to connect to the database, $id refers to the parameters required through GET The news ID passed in by the method. This code block uses the mysqli_connect() function to connect to the database, then executes the SELECT statement and stores the result in the $result variable, and finally obtains the row data in the result set through the mysqli_fetch_assoc() function and stores it in the $row variable. Finally, use the mysqli_free_result() function to release the result set, and use the mysqli_close() function to close the database connection.
This code will get the id from the PHP program and dynamically add it to the href attribute so that the user can jump to the corresponding news page after clicking the link.
At the same time, in In the PHP program, we need to obtain the id passed in from the front desk through the $_GET[] method, then execute the SELECT statement mentioned above, obtain the news data, and finally output it to HTML. The specific implementation code is as follows:
$id = $_GET['id'];
$conn = mysqli_connect($host, $user, $pwd, $db);
$sql = "SELECT * FROM news WHERE id = '{ $id}'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
mysqli_free_result($result);
mysqli_close($conn) ;
?>
This code appends the output of the PHP program to HTML and dynamically renders news titles and content based on the data queried from the database.
index.php (news list page):
< ;head>
$conn = mysqli_connect($host, $user, $pwd, $db); $sql = "SELECT * FROM news"; $result = mysqli_query($conn, $sql); while ($row = mysqli_fetch_assoc($result)) {
?>
<li><a href="view_news.php?id=<?php echo $row['id']; ?>"><?php echo $row['title']; ?></a></li>
} mysqli_free_result($result); mysqli_close($conn);
?>