gpt4 book ai didi

php - 在表中显示数据库中的数据

转载 作者:搜寻专家 更新时间:2023-10-30 22:09:07 24 4
gpt4 key购买 nike

我有这样的东西,该函数允许我显示来自数据库“demo”和“products”表的数据:

class Product
{
private $conn;
private $id;
private $name;
private $description;
private $price;
private $category_id;
private $category_name;
private $created;

public function __construct($db)
{
$this->conn = $db;
}

public function readAll()
{
$stmt = $this->conn->prepare('SELECT name, description, price, CategoryID, created FROM products');
$stmt->execute();
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
$n = $result['name'];
$d = $result['description'];
$p = $result['price'];
$ca = $result['CategoryID'];
$c = $result['created'];
echo $n . " - " . $d . " - " . $p . " - " . $ca . " - " . $c . "<br />" . "<br />";
}
}
}

这是我的数据库连接:

class Database {

public function getConnection() {
$result = false;
try {
$result = new PDO('mysql:host=localhost;dbname=demo', 'root', '');
} catch(PDOException $e) { }
return $result;
}
}
$db = new Database();
$conn = $db->getConnection();
if (!$conn) {
die("Error connecting to the database");
}

我可以这样显示数据:

<div>
<h3>readAll:</h3>
<form action="" method="post">
<label>Products: <br /> (Name - Description - Price - Category ID - Creation date): </label><br />
<?php
$cat = new Product($conn);
echo $cat->readAll();
?>
</form>
</div>

但是如何在表格中显示数据库中的数据呢?

最佳答案

这是一条线索,这完全取决于您的 php 结构。

就在while循环之前,

  echo '<table>';

//如果你愿意,你可以添加表头

 While(...){

$a = $row['...'];

echo '
<tr><td>'.$a.'</td></tr>
';
//you can add as many columns as you wish

}

echo '</table>

希望你能从中得到理解

关于php - 在表中显示数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37273442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com