我不确定为什么下面的语句基本上不工作,简而言之,我希望它运行$result
语句,如果只有$product_id
没有在$images
表中找到。如果找到它,我希望它然后运行inner
语句。
两个语句都通过phpMyAdmin和$result
语句工作时,只使用$this->db->query
代码:
public function product_delete($product_id)
{
$table = $this->_table_products;
$images = $this->_table_product_images;
$result = $this->db->query("SELECT `id` FROM $table WHERE $table.id ='$product_id'");
if(mysqli_num_rows($result) !== 0)
{
$this->db->query("DELETE FROM $table WHERE $table.id = '$product_id'");
}else{
$this->db->query("DELETE FROM $table INNER JOIN $images ON $table.id = $images.product_id WHERE $images.id = $product_id");
}
}
您必须在查询中使用{}
围绕变量名称。使用!=
代替!==
$result = $this->db->query("SELECT `id` FROM {$table} WHERE {$table}.id ='$product_id'");
if(mysqli_num_rows($result) != 0)
{
$this->db->query("DELETE FROM {$table} WHERE {$table}.id = '$product_id'");
}else{
$this->db->query("DELETE FROM {$table} INNER JOIN {$images} ON {$table}.id = {$table}.product_id WHERE {$images}.id = $product_id");
}
将!==
更改为!=
if(mysqli_num_rows($result) != 0)
{
$this->db->query("DELETE FROM $table WHERE $table.id = '$product_id'");
}
else
{
$this->db->query("DELETE FROM $table INNER JOIN $images ON $table.id = $images.product_id WHERE $images.id = $product_id");
}
如果要检查images表,应该查询${images}
表,而不是${table}
表。此外,如果您只对找出有多少匹配行感兴趣,最好使用MySQL中的COUNT()
函数。这样你总是得到一行,而不是10万。使用mysqli_num_rows()
函数的缺点是,您将失去CodeIgniter数据库类引入的灵活性。
$result = $this->db->query("SELECT COUNT(*) `cnt` FROM ${images} WHERE ${images}.product_id ='$product_id'");
$row = $result->row();
if($row['cnt'] != 0) {
// found something
如果变量名在字符串中不清楚,你可以使用括号告诉PHP你想要什么。"${foo}bar"
表示变量是$foo
,而bar
只是附加到变量内容上的字符串。这也有助于提高可读性。我将!==
更改为!=
,因为我对CI不够熟悉,我不知道该值是否将是整数或整数的字符串表示形式。