我正在尝试删除其中包含外键的列。我在这上面坐了一段时间,感觉就像我在监督某些东西,而遮阳篷一定很明显,但我就是不明白。 我从日志中得到的错误是:
PHP Fatal error: Cannot declare class User, because the name is already in use user_id is a foreign key of the Identifier from the Class user.
我使用的数据库是InnoDB。我已经尝试过:
$drop = 'ALTER TABLE `Group` DROP FOREIGN KEY `user_id`';
$stmt = $conn->prepare($drop);
$stmt->execute();
但是这没有任何效果,日志中没有错误或任何东西。
如果这是显而易见的,我深表歉意,我是一名学生,这是我的第三周。 ́_(ツ)_/́
<?php
require 'connect.php';
require 'model.php';
$identifier = null;
if(!empty($_GET['identifier'])) {
$identifier = $_REQUEST['identifier'];
}
if(!empty($_POST)) {
require 'connect.php';
require 'model.php';
$identifier = $_REQUEST['identifier'];
settype($identifier, 'integer');
$group = Group::retrieve($conn, $_GET['identifier']);
Group::delete($conn, $group);
header('Location: view.php');
} else {
echo 'Its not working';
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<link href='bootstrap/bootstrap/css/bootstrap.min.css' rel='stylesheet'>
<script src='bootstrap/bootstrap/js/bootstrap.min.js'></script>
</head>
<body>
<div class='container'>
<div class='span10 offset1'>
<div class='row'>
<h3>Delete</h3>
</div>
<form class='form-horizontal' action='delete.php?identifier=<?php echo $identifier?>' method='post'>
<input type='hidden' name='identifier' value='<?php echo $identifier;?>'/>
<p class='alert alert-error'>DO YOU REALLY WANT TO Delete?</p>
<div class='form-actions'>
<button type='submit' class='btn btn-danger'>EXTERMINATE</button>
<a class='btn' href='view.php'>No</a>
</div>
</form>
</div>
</div>
</body>
</html>
我的模型中类组的相关部分如下所示:
public static function retrieve($conn, $identifier) {
$query = 'SELECT * FROM `Group` WHERE `identifier` = :identifier';
$stmt = $conn->prepare($query);
$stmt->bindParam(':identifier', $identifier, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return new Group((int)$result['identifier'], $result['admin'],
$result['superuser'], $result['testaccount'], (int)$result['user_id']);
}
public static function delete($conn, Group $group) {
$query = 'DELETE FROM `Group` WHERE identifier = :identifier, admin = :admin,
superuser = :superuser, testaccount = :testaccount, user_id = :user_id';
$stmt = $conn->prepare($query);
$stmt->bindValue(':identifier', $group->getIdentifier(), PDO::PARAM_INT);
$stmt->bindValue(':admin', $group->getAdmin(), PDO::PARAM_STR);
$stmt->bindValue(':superuser', $group->getSuperuser(), PDO::PARAM_STR);
$stmt->bindValue(':testaccount', $group->getTestaccount(), PDO::PARAM_STR);
$stmt->bindValue(':user_id', $group->getUser_id(), PDO::PARAM_INT);
$stmt->execute();
return TRUE;
}
最佳答案
如果您在 MySql 控制台中查询失败,请选中此项。如果失败则意味着约束名称可能不正确。如果是这种情况,请尝试以下代码。 必须使用其约束名称而不是列名称来删除外键。
要获取可以使用的约束名称
SHOW CREATE TABLE Group
ALTER TABLE `Group` DROP FOREIGN KEY `your_constraint_name_here`
更多信息请访问
关于php - 删除带有外键的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52252674/