以下代码对我至少是直截了当的。我想用PDO实现同样的目的。但是,试着尽可能地让我无法理解这个概念。有人可以解释一下吗?
//Connect to a database.
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die("Couldn't connect to database.");
//Delete from the multiple tables.
$sql = "DELETE FROM table1, table2, tables3, tables4 WHERE id='75'";
$result = mysqli_query($link , $sql);
答案 0 :(得分:1)
您无法在单个查询中执行多个表删除尝试使用PDO中的foreach
$pdo = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$tables = array("table1","table2","table3","table4");
foreach($tables as $table) {
$sql = "DELETE FROM $table WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id); // $id or '75'
$stmt->execute();
}
答案 1 :(得分:1)
在这里,使用预处理语句只是为了显示为id = 75是没有用户输入 - 但这是更好的方式和使用事务 - 如果你想一次删除/更新/插入更多数据这是方式更快。
$id = 75;
try {
$pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME , DB_USER, DB_PASS);
$pdo->beginTransaction();
$st = $pdo->prepare('DELETE FROM table1 WHERE id = :id');
$st->execute(array(':id', $id));
$st = $pdo->prepare('DELETE FROM table2 WHERE id = :id');
$st->execute(array(':id', $id));
$st = $pdo->prepare('DELETE FROM table3 WHERE id = :id');
$st->execute(array(':id', $id));
$st = $pdo->prepare('DELETE FROM table4 WHERE id = :id');
$st->execute(array(':id', $id));
$pdo->commit();
}
catch (PDOException $e) {
die('Error!: ' . $e->getMessage() . '<br/>');
}
<强>旁注:强>
要少写,请这样做:
$array = array('table1','table2','table3','table4');
foreach ($array as $table) {
$st = $pdo->prepare('DELETE FROM '.$table.' WHERE id = :id');
$st->execute(array(':id', $id));
}