简体   繁体   中英

How to delete rows in multiple tables using pdo

I am trying to delete category and products belong to it in products_TABLE using pdo INNER JOIN. it works if I delete only category without deleting products. Here is my code :

$catid = filterString($_GET['cat_id']);
$stmt = $pdo->prepare('DELETE FROM categories AS c
                        INNER JOIN products AS p ON c.cat_id = p.catid
                        WHERE cat_id = :cat_id
                        ');
$delete = $stmt->execute(array('cat_id' =>$catid));

This is the error I am having :

Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in D:\\wamp\\www\\p\\employees\\DelStore.php:25 Stack trace: #0 D:\\wamp\\www\\p\\employees\\DelStore.php(25): PDOStatement->execute(Array)

1 {main} thrown in D:\\wamp\\www\\p\\employees\\DelStore.php on line 2

I understand it says given parameters are invalid, But couldnt solve how to give parameters in:

$delete = $stmt->execute(array('cat_id' =>$catid));

Thanks for any advice

The error you are getting is because you have :products.catid Change that to products.catid

Also if you want to delete the entries from both tables you shoul use aliases.

DELETE c,p FROM categories c
INNER JOIN products p ON c.cat_id = p.catid
WHERE cat_id = :cat_id

Also you need to change

$delete = $stmt->execute(array('cat_id' =>$catid));

to

$delete = $stmt->execute(array(':cat_id' =>$catid));

The above example doesn't work if you are using a SQL Server. In that case you should be using 2 seperate delete queries.

Also when you bind parameters in the execute function as an array thay are binded as stings. This might also cause some problems depending on your database structure. Using $stmt->bindParam() is usually a better option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM