2

I was wondering if there was a way to create a new user for my MySQL Database? 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. Again, if they don't have one, then I want to create a new one.

2
  • Are you trying to have input fields on the page for the user to enter the fields? Commented Oct 30, 2015 at 2:40
  • Yea, I have that already. The main issue I'm having is creating new database users. Basically, I'm trying to create a contacts page that will store all your contacts once you create an account(database user that stores all your contacts). I have to be able to create a new user through my PhP code; no idea how. @KingCodeFish Commented Oct 30, 2015 at 2:45

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

This is perfectly possible, but one thing I would stay clear of is logging in as root to do these commands.

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.