I have two tables named users
and contacts
. I would like to delete the records from two table at once. For that I am using the code below for now.
public function delete($userId, $contactId) {
/* Since Values cannot be mixed (the Numbers) with control flow logic
(the commas) with prepared statements needs one placeholder per Value. */
//As many question marks as array entries; the last one needs no comma
$questionMarks = str_repeat("?,", count($userId)-1)."?";
$sth = $this->dbh->prepare("DELETE FROM users WHERE id IN($questionMarks)");
$sth->execute($userId);
$questionMarks = str_repeat("?,", count($contactId)-1) . "?";
$sth = $this->dbh->prepare("DELETE FROM contacts WHERE id IN($questionMarks)");
$sth->execute($contactId);
}
Please note that $userId
and $contactId
will be an array and the count will always be equal.
How do I merge these two queries into one?
ANSWER :
The below query worked for me.
DELETE users,contacts FROM users INNER JOIN contacts WHERE users.id IN (开发者_运维技巧2) AND contacts.id IN (2);
The answer to this question lies, according to me, Not in your pHp statements or even in your query but in HOW you created your tables in database. When you created your table you must have specified a FOREIGN KEY relationship and then an ON DELETE CASCADE will solve all the reference problems when the parent row is deleted all the refering rows with the ON DELETE CASCADE will also be deleted.
so it may be something like this in your sql for contacts
FOREIGN KEY id REFERENCES users(id) ON DELETE CASCADE
depending on the database you use.
You need to find the way to join the tables together and use a query like
DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;
精彩评论