Beberapa catatan umum:Jangan gunakan bindParam()
kecuali jika Anda menggunakan prosedur yang mengubah nilai parameter Oleh karena itu, use bindValue()
. bindParam() menerima nilai argumen sebagai variabel yang direferensikan. Itu berarti Anda tidak dapat melakukan $stmt->bindParam(':num', 1, PDO::PARAM_INT);
- menimbulkan error. Selain itu, PDO memiliki fungsi sendiri untuk mengontrol transaksi, Anda tidak perlu mengeksekusi query secara manual.
Saya menulis ulang kode Anda sedikit untuk menjelaskan bagaimana PDO dapat digunakan:
if($_POST['groupID'] && is_numeric($_POST['groupID']))
{
// List the SQL strings that you want to use
$sql['privileges'] = "DELETE FROM users_priveleges WHERE GroupID=:groupID";
$sql['groups'] = "DELETE FROM groups WHERE GroupID=:groupID"; // You don't need LIMIT 1, GroupID should be unique (primary) so it's controlled by the DB
$sql['users'] = "DELETE FROM users WHERE Group=:groupID";
// Start the transaction. PDO turns autocommit mode off depending on the driver, you don't need to implicitly say you want it off
$pdo->beginTransaction();
try
{
// Prepare the statements
foreach($sql as $stmt_name => &$sql_command)
{
$stmt[$stmt_name] = $pdo->prepare($sql_command);
}
// Delete the privileges
$stmt['privileges']->bindValue(':groupID', $_POST['groupID'], PDO::PARAM_INT);
$stmt['privileges']->execute();
// Delete the group
$stmt['groups']->bindValue(":groupID", $_POST['groupID'], PDO::PARAM_INT);
$stmt['groups']->execute();
// Delete the user
$stmt['users']->bindParam(":groupID", $_POST['groupID'], PDO::PARAM_INT);
$stmt['users']->execute();
$pdo->commit();
}
catch(PDOException $e)
{
$pdo->rollBack();
// Report errors
}
}