简体   繁体   English

如何使用PDO删除多个表中的行

[英]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. 我正在尝试使用pdo INNER JOIN删除products_TABLE中的类别及其所属的产品。 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) 致命错误:未捕获的PDOException:SQLSTATE [HY093]:无效的参数编号:在D:\\ wamp \\ www \\ p \\ employees \\ DelStore.php:25中未定义参数:堆栈跟踪:#0 D:\\ wamp \\ www \\ p \\ employee \\ DelStore.php(25):PDOStatement-> execute(Array)

1 {main} thrown in D:\\wamp\\www\\p\\employees\\DelStore.php on line 2 在第2行的D:\\ wamp \\ www \\ p \\ employees \\ DelStore.php中抛出1个{main}

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 您收到的错误是因为您有:products.catid将此更改为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. 如果您使用的是SQL Server,则上面的示例不起作用。 In that case you should be using 2 seperate delete queries. 在这种情况下,您应该使用2个单独的删除查询。

Also when you bind parameters in the execute function as an array thay are binded as stings. 同样,当您在execute函数中将参数绑定为数组时,thay也会被绑定为字符串。 This might also cause some problems depending on your database structure. 根据您的数据库结构,这也可能会导致一些问题。 Using $stmt->bindParam() is usually a better option. 使用$stmt->bindParam()通常是一个更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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