views:

212

answers:

2

I have the following PHP code that i use to create a database, a user, and grant permissions to the user:

$con = mysql_connect("IP.ADDRESS","user","pass");
mysql_query("CREATE DATABASE ".$dbuser."",$con)or die(mysql_error());
mysql_query("grant all on ".$dbuser.".* to  ".$dbname." identified by '".$dbpass."'",$con) or die(mysql_error());

I want to perform these same actions but from within a shell script. Is it just something like this:

MyUSER="user"
MyPASS="pass"
MYSQL -u $MyUSER -h -p$MyPASS -Bse "CREATE DATABASE $dbuser;"
MYSQL -u $MyUSER -h -p$MyPASS -Bse "GRANT ALL ON $DBUSER.* to  $DBNAME identified by $DBPASS;"

EDIT as this is needed within postwwwacct (a cPanel post account creation hook script) ideally it will be entirely self-contained

+1  A: 

Your quotes and capitalization is a bit off (or platform biased), but in essence yes.

You might want to consider actually having your script create an sql script, then making it run through php, shell(s!), etc will be much easier.

Unreason
I second using a SQL script for that. Have a look a dbdeploy and phing http://www.davedevelopment.co.uk/2008/04/14/how-to-simple-database-migrations-with-phing-and-dbdeploy/
Gordon
ideally i would keep it within this one script, its being run from postwwwacct (a cpanel post account creation script) so ideally it would be entirely self-contained
seengee
@Unreason could you let me know where the quotes and caps are off so i can fix them please
seengee
.. or give an example of it creating an SQL script and executing that. thanks
seengee
+2  A: 

You need to lower-case "MYSQL" and add a hostname after the -h and you've mixed single and double quotes. Also, you need to set the values for dbname, dbuser and dbpass and use consistent capitalization.:

MyUSER="user"
MyPASS="pass"
HostName="host"
dbName="dbname"
dbUser="dbuser"
dbPass="dbpass"

mysql -u $MyUSER -h $HostName -p$MyPASS -Bse "CREATE DATABASE $dbUser;"
mysql -u $MyUSER -h $HostName -p$MyPASS -Bse "GRANT ALL ON ${dbUser}.* to $dbName identified by $dbPass;"

But I'm not 100% confident in your SQL syntax. I would think it would look more like this:

mysql -u $MyUSER -h $HostName -p$MyPASS -Bse "CREATE DATABASE $dbName;"
mysql -u $MyUSER -h $HostName -p$MyPASS -Bse "GRANT ALL ON ${dbName}.* to $dbUser identified by $dbPass;"
Dennis Williamson