0

I want to Create mysql user and database using php script

how to create mysql user using mysql_query()

<?php
    mysql_query("CREATE USER 'demodemodemo'@'localhost' IDENTIFIED BY 'jayul321';");
?>

this is not working..

1
  • That would work if the connected user has privileges to grant permissions to the new user. You need to check for errors mysql_query(...) or die(mysql_error()); Of course, use caution when creating users from application code. It is an exotic use case to be creating database users in an application unless the application is a database management client Commented Mar 7, 2015 at 12:41

1 Answer 1

2

PHP script to create MySQL database, add user and grant privileges.

## make sure you connect first to mysql with a super user (ex: root)
mysql_connect('localhost', 'root', 'password');

$dbName = 'database_name'; // new database name
$dbUser = 'db_user';       // new user name
$dbPass = 'db_pass';       // new user password

$queries = array(
    "CREATE DATABASE `$dbName` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci",
    "CREATE USER '$dbUser'@'localhost' IDENTIFIED BY '$dbPass'",
    "GRANT USAGE ON * . * TO '$dbUser'@'localhost' IDENTIFIED BY '$dbPass' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0",
    "GRANT SELECT , INSERT , UPDATE, DELETE ON `$dbName` . * TO '$dbUser'@'localhost'",
    "FLUSH PRIVILEGES"
);

foreach($queries as $query) {
    echo 'Executing query: "'.htmlentities($query).'" ... ';
    $rs = mysql_query($query);
    echo ($rs ? 'OK' : 'FAIL') . '<br/><br/>';
}
Sign up to request clarification or add additional context in comments.

2 Comments

what 0 represent on MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0
0 means unlimited: "To remove a limit, set its value to zero" Source: MySQL manual: dev.mysql.com/doc/refman/5.0/en/user-resources.html

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.