Search code examples
phpmysqlpdodelete-rowcorresponding-records

Can't delete multiple rows from MySQL table in a loop


I'm trying to delete all the rows matching a pair of conditions from a mySQL table using php's PDO object. I can't figure out why it isn't working:

//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'"
);

//Deleting the post itself works, but the part inside the foreach loop doesn't for some reason. For debugging I added the following inside the loop:

echo "WHERE cid = '{$this->row['cid']}'";

And it returned just as expected:

WHERE cid = '1'
WHERE cid = '2'

So the data that is being fetched isn't the issue. I also tried

WHERE id = '$html_data->id' AND pid = '$html_data->pid' AND cid = '$this->row['cid']'"

Instead of using just the cid and it also didn't work. Echoing it returns, as expected:

WHERE id = '1' AND pid = '1' AND cid = '1'
WHERE id = '1' AND pid = '1' AND cid = '2'

And yes, I checked the comments table, id, pid and cid that I want to delete matches those that are being echoed.


Solution

  • It should be

    $this->db->exec(
    "DELETE from comments 
    WHERE cid = '$this->row[cid]'"
    );
    

    OR you can also use

    $this->db->exec(
    "DELETE from comments 
    WHERE cid = '{$this->row['cid']}'"
    );