我正在尝试使用 php 的 PDO 对象从 mySQL 表中删除与一对条件匹配的所有行。我不明白为什么它不起作用:
//This deletes all comments for a given post;
//Querying database for existent comments on that post;
$this->query = $this->db->query(
"SELECT cid
FROM comments
WHERE id = '$html_data->id' AND pid = '$html_data->pid'"
);
//Fetching results into an array;
$this->rows = $this->query->fetchAll(PDO::FETCH_ASSOC);
//Deleting each comment on that post;
foreach ($this->rows as $this->row) {
$this->db->exec(
"DELETE from comments
WHERE cid = '$this->row['cid']'"
);
};
//Deleting the post itself;
$this->db->exec(
"DELETE from posts
WHERE id = '$html_data->id' AND pid = '$html_data->pid'"
);
//删除帖子本身
可以工作,但foreach
循环内的部分由于某种原因不起作用。为了调试,我在循环内添加了以下内容:
echo "WHERE cid = '{$this->row['cid']}'";
它按预期返回:
WHERE cid = '1'
WHERE cid = '2'
所以正在获取的数据不是问题。我也尝试过
WHERE id = '$html_data->id' AND pid = '$html_data->pid' AND cid = '$this->row['cid']'"
而不是仅使用cid
,它也不起作用。正如预期的那样,它会返回:
WHERE id = '1' AND pid = '1' AND cid = '1'
WHERE id = '1' AND pid = '1' AND cid = '2'
是的,我检查了我想要删除的 comments
表、id
、pid
和 cid
匹配那些正在回显的内容。
最佳答案
因此,解决此问题的更好方法是使用准备好的语句并从查询中获取变量。这样,您既可以解决这个问题,也可以解决您现在遇到的安全问题(SQL 注入(inject))...
这是转换为高效准备语句的代码:
$stmt= $this->db->prepare(
"SELECT cid
FROM comments
WHERE id = ? AND pid = ?"
);
$this->query = $stmt->execute(array($html_data->id, $html_data->pid));
$this->rows = $this->query->fetchAll(PDO::FETCH_ASSOC);
$deleteStmt = $this->db->prepare(
"DELETE from comments
WHERE cid = ?"
);
foreach ($this->rows as $row) {
$deleteStmt->execute(array($row['cid']));
};
//Deleting the post itself;
$stmt = $this->db->prepare(
"DELETE FROM posts
WHERE id = ? AND pid = ?"
);
$stmt->execute(array($html_data->id, $html_data->pid));
但是,您可以进一步清理它。处理这个问题的最佳方法是使用外键。例如,让我们从评论表的 pid
到 posts id
字段创建一个外键。
CREATE TABLE posts (
id INT,
name VARCHAR(35),
PRIMARY KEY (`id`)
) ENGINE = InnoDB;
CREATE TABLE comments (
id INT,
pid INT,
name VARCHAR(35),
PRIMARY KEY (`id`),
CONSTRAINT `posts_id`
FOREIGN KEY `posts_id` (`pid`)
REFERENCES `posts` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE = InnoDB
这里的美妙之处在于你的大代码块简化为这样:
$stmt = $this->db->prepare(
"DELETE FROM posts
WHERE id = ? AND pid = ?"
);
$stmt->execute(array($html_data->id, $html_data->pid));
当你删除评论时,约束(外键)会自动级联删除来删除评论(因为如果不这样做,就会有一个无效的约束)...
关于php - 无法在循环中从 MySQL 表中删除多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15474609/