How to use PHP to develop a simple product review function
With the rise of e-commerce, the product review function has become an indispensable function to facilitate the interaction between users communication and consumers’ evaluation of products. This article will introduce how to use PHP to develop a simple product review function, and attach specific code examples.
First, we need to create a database to store product review information. Create a database named "product_comments" and create a table named "comments" in it. The table structure is as follows:
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY, product_id INT, username VARCHAR(50), comment TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
In the PHP code, we need to connect to the database. Create a file named "config.php" with the following content:
$host = 'localhost';
$dbname = 'product_comments';
$username = 'root';
$password = 'password';
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
Please make sure to replace $host, $dbname, $username and $password with yours own database information.
In the product details page, we need to display the review information of the product. Create a file called "product.php" and add the following code in it:
include 'config.php';
$product_id = $_GET ['product_id'];
$stmt = $conn->prepare('SELECT * FROM comments WHERE product_id = :product_id');
$stmt->bindParam(':product_id', $product_id);
$stmt->execute();
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($comments as $comment) {
echo '<p>' . $comment['username'] . '于' . $comment['created_at'] . '发表评论:<br>' . $comment['comment'] . '</p>';
}
?>
Please note that in the above code, we obtain the ID of the product through the GET method, then query the review information of the product from the database, and add it Displayed on the product detail page.
In order to add a comment, we need to add a comment form to the product details page. Add the following code in the "product.php" file: