[英]How to create a new mySQL database user from php
I was wondering if there was a way to create a new user for my MySQL Database?我想知道是否有办法为我的 MySQL 数据库创建一个新用户? I'm trying to add basic log-in functionality that will allow the user to connect to database.
我正在尝试添加允许用户连接到数据库的基本登录功能。 If user has no account, then I want to create a new one.
如果用户没有帐户,那么我想创建一个新帐户。 This is what I have so far:
这是我到目前为止:
<html>
<head>
<title>Test</title>
</head>
<body>
<?php
$username = "root";
$password = "root";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("contactsDB",$dbhandle)
or die("Could not select examples");
echo "Found contacts DB";
?>
</body>
Everything connects properly, but now, instead of having to type in the username and password (root), I want user to type their username and password.一切都正常连接,但现在,我希望用户输入他们的用户名和密码,而不是输入用户名和密码(root)。 Again, if they don't have one, then I want to create a new one.
同样,如果他们没有,那么我想创建一个新的。
You need atleast one admin account to create a user with less privilege.您至少需要一个管理员帐户才能创建权限较低的用户。
Please refer to create db and user mysql and set privileges php which is a good reference.请参考create db and user mysql and set privileges php ,这是一个很好的参考。
This is perfectly possible, but one thing I would stay clear of is logging in as root to do these commands.这是完全可能的,但我要避免的一件事是以 root 身份登录来执行这些命令。
With that in mind a method similar to this may work.考虑到这一点,类似于此的方法可能会奏效。
mysql_connect('localhost', 'user', password);
mysql_query("CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';");
mysql_query("GRANT ALL ON db1.* TO 'username'@'localhost'");
mysql_close();
If you have a dedicated database for these new users, you can easily assign it then.如果您有这些新用户的专用数据库,那么您可以轻松地分配它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.