,可以按照以下步骤进行操作:
<?php
$servername = "数据库服务器地址";
$username = "数据库用户名";
$password = "数据库密码";
$dbname = "数据库名";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
?>
CREATE TABLE products (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10,2) NOT NULL,
description TEXT
);
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$price = $_POST["price"];
$description = $_POST["description"];
// 准备插入语句
$sql = "INSERT INTO products (name, price, description) VALUES ('$name', $price, '$description')";
if ($conn->query($sql) === TRUE) {
echo "产品添加成功";
} else {
echo "添加产品时出错: " . $conn->error;
}
}
?>
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<div class="form-group">
<label for="name">产品名称:</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="form-group">
<label for="price">产品价格:</label>
<input type="number" step="0.01" class="form-control" id="price" name="price" required>
</div>
<div class="form-group">
<label for="description">产品描述:</label>
<textarea class="form-control" id="description" name="description" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">添加产品</button>
</form>
<?php
// 查询所有产品
$sql = "SELECT * FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<div class='row'>";
echo "<div class='col-md-4'>" . $row["name"] . "</div>";
echo "<div class='col-md-4'>" . $row["price"] . "</div>";
echo "<div class='col-md-4'>" . $row["description"] . "</div>";
echo "</div>";
}
} else {
echo "暂无产品";
}
?>
通过以上步骤,你可以在PHP SQL中添加数据库中的产品,并使用Bootstrap网格系统显示出来。请注意,这只是一个简单的示例,实际应用中可能需要更多的安全性和错误处理。
领取专属 10元无门槛券
手把手带您无忧上云