In a shell script, create a database if it does not exist

Key words and phrases: 
mysql create database from bash script mysql if database exists automate creation of database if it doesn't already exist PHP script bash script if mysql database does not exist create
Description & Info: 

Use the MySQL: SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'database_name'

<?php
if (mysql_num_rows(mysql_query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '". $dbname ."'"))) {
  echo
"Database $dbname already exists.";
}
else {
 
// go on and create the user, database, etc.
  // create the user

 
if (!mysql_query("CREATE USER '". $dbuser ."'@'%' IDENTIFIED BY '". $dbpass ."'"))  die(mysql_error());
  echo
"User $dbuser created.\n";

 
// does this do anything
 
if (!mysql_query("GRANT USAGE ON * . * TO '". $dbuser ."'@'%' IDENTIFIED BY '". $dbpass ."' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0")) die(mysql_error());
  echo
"Granted usage.\n";
 
 
// create the database.
  // CREATE DATABASE `livingcon_live` ;
 
if (!mysql_query("CREATE DATABASE `". $dbname. "`"))  die(mysql_error());
  echo
"Database $dbname created.\n";
 
 
// GRANT ALL PRIVILEGES ON `livingcon_live` . * TO 'livingcon_live'@ '%';  -- spaces don't work b/n @ and %
 
if (!mysql_query("GRANT ALL PRIVILEGES ON `". $dbname ."` . * TO '". $dbuser ."'@'%'"))  die(mysql_error());
  echo
"Granted privileges of user $dbuser to database $dbname \n";
 
  echo
"Copy and save this password for use on the Drupal install page, if needed:\n $dbpass \n";
}
?>

That's pretty much the whole PHP abomination which can be found at scripts/_agaric_makedatabase.sh

Alternate, better methods of creating the database, not used at the moment:

Bash: http://drupal.org/node/196417 (First Draft of BASH script for creating new multisite)
Perl: system('mysql -u *** -p -e \'create database activity_1_'.$date.'\'');

For another way of checking if a database exists, see:

http://articles.techrepublic.com.com/5100-10878_11-1045433.html

by Benjamin Melançon
Posted on Tue, 2008-07-01 08:16
in
Post new comment
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote> <h1> <h2> <h3> <h4> <h5> <h6> <small> <pre> <strike> <sub> <sup>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.