从MySQL删除用户不起作用

时间:2015-04-21 10:49:29

标签: php mysql sql-delete

我正在尝试从MySQL服务器中删除用户:

$conn = new PDO("mysql:host=$host;port=$port;dbname=mysql;charset=utf8","$adminname", "$pass",array( PDO::ATTR_PERSISTENT => true));
$sql_deleteuser="DELETE FROM `mysql`.`user` WHERE `user`.`User` = '$username'";                 
//$sql_deleteuser="SELECT `User` FROM `mysql`.`user`";  
$PDOStatement3=$conn->prepare($sql_deleteuser);
//$PDOStatement3->bindParam(':username', $username, PDO::PARAM_STR);   
$res_exec=$PDOStatement3->execute();

但它在errorInfo()中没有工作且没有错误,我尝试了

$sql_deleteuser="DROP USER '$username'@'%'";

$sql_deleteuser="IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'$username') DROP USER [$username]";同样的结果。

连接很好我用SELECT查询测试它并且它可以工作。

我有没有想念。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

要么您没有放弃用户的权限/权利

  

DROP USER语句删除一个或多个MySQL帐户。   要使用它,您必须具有mysql数据库的DELETE权限

也许问题是用户有一个开放的连接 因为mysql doc说:

  

重要

     

DROP USER 不会自动关闭任何打开的用户   会话。相反,如果具有开放会话的用户是   删除后,该语句在该用户的会话之前不会生效   关闭了。会话关闭后,用户将被删除   用户下次登录尝试将失败。这是设计的。

如何终止连接请参阅以下答案:

how to kill mySQL connections

见DOC:

https://dev.mysql.com/doc/refman/5.0/en/drop-user.html

答案 1 :(得分:0)

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//Edit: Use REVOKE to revoke the privileges. This removes rows for the account from all the grant tables except the user table, and revokes any global privileges listed in the user table.

// sql to delete a record, use $host to remove a specific user
$sql = "DELETE FROM `mysql`.`user` WHERE `user`.`User` = '$username" AND `user`.`Host` = '$host";


// use exec() because no results are returned
$conn->exec($sql);
echo "Record deleted successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

尝试上面的代码,你也会发现错误!