PHP query product information

王林
Release: 2024-04-09 15:54:01
Original
510 people have browsed it

Querying product information in PHP involves the following steps: Establish a database connection. Prepare a query statement and specify the product ID to be queried. Bind the product ID parameter. Execute the query. Extract query results. Get product information and display it on the page.

PHP 查询商品信息

Use PHP to query product information

In e-commerce websites, it is usually necessary to query product information to display it to users or process orders. . PHP provides powerful database connection and query functions, which can easily query product information.

Database connection

// 数据库连接参数
$host = 'localhost';
$user = 'root';
$pass = '';
$dbName = 'ecommerce';

// 建立数据库连接
$conn = new mysqli($host, $user, $pass, $dbName);
Copy after login

Query product information

Product information is usually stored in the products of the database table. The following code shows how to query product information for a specified product ID:

// 商品 ID
$productId = 1;

// 准备查询语句
$stmt = $conn->prepare("SELECT * FROM products WHERE id = ?");
// 绑定参数
$stmt->bind_param('i', $productId);
// 执行查询
$stmt->execute();

// 提取查询结果
$result = $stmt->get_result();
// 获取商品信息
$productInfo = $result->fetch_assoc();

echo $productInfo['name']; // 输出商品名称
Copy after login

Practical case

Suppose we want to display the name, price and inventory quantity of the product on the product page. We can use the following code:

// 商品 ID
$productId = 1;

// 准备查询语句
$stmt = $conn->prepare("SELECT name, price, quantity FROM products WHERE id = ?");
// 绑定参数
$stmt->bind_param('i', $productId);
// 执行查询
$stmt->execute();

// 提取查询结果
$result = $stmt->get_result();
// 获取商品信息
$productInfo = $result->fetch_assoc();

// 输出商品信息
echo "<h1>{$productInfo['name']}</h1>";
echo "<p>价格:{$productInfo['price']}</p>";
echo "<p>库存:{$productInfo['quantity']}</p>";
Copy after login

Through the above code, we successfully query the name, price and stock quantity of the specified product and display it on the product page.

The above is the detailed content of PHP query product information. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!