Create a new database with Mysql user and password directly from PHP

Asked

Viewed 783 times

1

Is it possible to create a new database with Mysql user and password directly from the PHP script? I ask because we are finalizing a registration system where each client will have its own database. If so, could you provide an example? I understand that to create a database, I can use:

mysqli_query($conexaoPrimaria,"CREATE DATABASE ".$banco." ");

But the user ( with all permissions ) and password?

=====================

REPLY

I was able to solve it this way:

mysqli_query($conexao,"CREATE USER 'novo_usuario'@'localhost' IDENTIFIED WITH mysql_native_password AS 'senha_usuario'");
mysqli_query($conexao,"GRANT ALL PRIVILEGES ON *.* TO 'novo_usuario'@'localhost' REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;");
mysqli_query($conexao,"GRANT ALL PRIVILEGES ON `novo_usuario`.* TO 'novo_usuario'@'localhost';");
mysqli_query($conexao,"GRANT ALL PRIVILEGES ON `novo_usuario\_localhost`.* TO 'novo_usuario'@'localhost';");

======================

  • Hello Bacco, yes, I had already seen this post, but for me it did not serve, because it is very vague and without examples as I requested.

  • 1

    When there is a question similar to yours and you don’t have a good answer, you can put reputable points in it to attract new answers. Doubling the doubt is not the appropriate way in these cases.

  • Right, but how do I do it? Is it still possible to receive answers in this post? Because I was able to solve and would like to share.

  • 1

    No, if you have something to add, it would be the case to adapt to the original post "Create Mysql user and database via PHP". So it is good for anyone who finds any of the two questions, since yours will always serve as an index for that. It would be nice if @Darlei passed his there too.

2 answers

2

This is possible, but one thing that is clear, do not sign in as root to do these commands.

With that in mind, a method similar to this can 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 as quoted, you can easily assign it.

-2

To create a user you do not need to put a field for token , that would be permission, it is only necessary to generate this token and put in session ex:

$_SESSION['token'] = $tokenGerado;

the user table you create normally with your data

Browser other questions tagged

You are not signed in. Login or sign up in order to post.