【发布时间】:2019-08-26 22:28:28
【问题描述】:
我试图在每个类别上显示一个产品,从顶级父类别一直到该类别。我有这样的数据库设置:
CATEGORY TABLE:
id | parent_id | root_cat | name
5 37 0 bulbs
45 5 0 standard auxiliary
289 45 5 standard
297 289 5 5W
现在这是产品表:
id | name | cat
470 bulb 5w 297
这种情况正在发生,当我单击灯泡类别时,我看到的产品很好,但是当我单击子类别标准辅助时,我看不到产品。但是,如果我达到标准的另一个级别,我可以再次看到该产品,并且如果我点击 5W 猫,我也可以看到该产品。所以问题只在标准辅助类上。
这是我用来检索数据的方法: $table_2 是产品表,$table 是类别表。
public function getProductsWhereParentIdis($cat) {
$check = $this->checkCategoryChildren($cat);
if($check) {
$query = "
SELECT *
FROM categories
INNER JOIN products
ON products.category = categories.id
WHERE categories.id = '".$this->db->escape($cat)."'
OR categories.parent_id = '".$this->db->escape($cat)."'
OR categories.root_category = '".$this->db->escape($cat)."'";
return $this->db->fetchAll($query);
} else {
$query = "SELECT * FROM {$this->table_2} WHERE category = '".$this->db->escape($cat)."'";
return $this->db->fetchAll($query);
}
}
而且这个方法只是检查一个产品是否有父级:
public function checkCategoryChildren($id = null) {
if(!empty($id)) {
$query = "SELECT * FROM {$this->table} WHERE parent_id = '".$this->db->escape($id)."' ORDER BY view_order ASC";
return $this->db->fetchAll($query);
}
}
这是 fetchAll 方法:
public function query($query) {
$this->last_query = $query;
$result = mysqli_query($this->connection, $query);
$this->confirm_query($result);
return $result;
}
public function confirm_query($result) {
if(!$result) {
$output = "Database query failed<br />";
$output .= "Last SQL query: ". $this->last_query;
die($output);
} else {
$this->affected_rows = mysqli_affected_rows($this->connection);
}
}
public function fetchAll($query) {
$result = $this->query($query);
$output = array();
while($row = mysqli_fetch_assoc($result)) {
$output[] = $row;
}
mysqli_free_result($result);
return $output;
}
真的很期待任何人的建议,为什么我可以在除一个之外的所有类别中看到该产品,谢谢。
【问题讨论】:
-
有多少种组合?
-
我尝试了 3 次获取 id、parent_id 和另一个我没有输入但仍然没有得到预期效果的 root_parent
-
别担心 Dharman,我会转义每个查询,但您只是看不到它,因为我调用了不同类的方法,我在每个输入上调用的转义方法使我摆脱了任何 sql 注入
-
@Strawberry 我从语句中删除了内部,但它没有不同的效果
-
不是转义,问题是手动转义。使用带有占位符值的准备好的语句。这意味着更少的代码和更少的问题作为奖励。