我无法使用PHP OOP从MYSQL数据库中的表中显示数据。但是,我不确定是否无法显示数据,因为我一开始实际上并没有获取数据。
我尝试仅使用PHP数组而不使用HTML来获取和显示数据,但我发现这将无法正常工作,因为我没有使用HTML列表标签来格式化数据库中的数据。我曾经考虑过使用HTML表,但是我已经看到使用列表从数据库中进行显示的方式之前已经工作了好几次,而且我想知道为什么这样做不起作用。
我已经测试过MYSQL连接,并且确实存在。
* M_PRODUCTS.PHP *
<?php
class Products
{
private $Conn;
private $db_table = "toys";
function __construct() {
// here we're making sure that the connection from $conn in "init.php" is transferred
// into our own private $conn property for usage in this object
global $Conn;
$this->Conn = $Conn;
}
// fetches and displays all products from db
public function fetch_all_products($id = NULL)
{
if ($id == NULL)
{
$data = [];
if ($result = $this->Conn->query("SELECT * FROM " . $this->db_table . " ORDER BY name"))
{
if ($result->num_rows > 0)
{
while ($row = $result->fetch_array())
{
$data = array(
"id" => $row["product_id"],
"name" => $row["name"],
"price" => $row["price"],
"image" => $row["image"]
);
}
return $data;
}
else
{
return "<h1>Oops... Something went wrong!</h1>";
}
}
}
}
}
* INDEX.PHP *
<?php include("init.php");
include("models/m_products.php");
?>
<body>
<div id="whitespace">
<?php
$products = fetch_all_products();
我希望我的产品图像可以显示在index.html文件中。但是,什么也没有出现。
我也在JavaScript控制台中收到此错误消息:无法加载资源:服务器以状态404(未找到)进行了响应。这将解释很多,但是正如我所说,我测试了数据库连接,并且可以正常工作。如果我不使用JavaScript,则不确定该消息如何或为何从JavaScript控制台发出。我认为无论如何还是值得一提。
心有法竹
Cats萌萌
长风秋雁