Need to have databases created with a back end
application?This tutorial shows the database that was created from this
online application. It was pre filled with tables and data from another
script that ran right after the database was made.
Create a database on the fly
In
some recent work I needed to have databases created with a back end
application. Once the database was created from this online application
it was pre filled with tables and data from another script that ran
right after the database was made. To create a database with PHP we
first need to connect as a user that has the ability to create new
databases. Note that we are not connecting to a database but we are
connecting to MySQL as a user.
[php]
$link = mysql_connect(‘localhost’, ‘mysql_user’, ‘mysql_password’);
if (!$link) {
die(‘Could not connect: ‘ . mysql_error());
}
[/php]
After we have the connection we can simply call the following:
[php]
$dbname = $_POST['databasename']
// Your able to use a string here like: $dbname = ‘test_database’
// I am showing how you can get it from the POST.
// Also would be smart to check if the data sent is not empty with: if ( empty($dbname) ) {…
$sql = ‘CREATE DATABASE ‘ . $dbname;
if (mysql_query($sql, $link)) {
echo “Database my_db created successfully\n”;
} else {
echo ‘Error creating database: ‘ . mysql_error() . “\n”;
}
[/php]
This can become dynamic if you use it in conjunction with a text filed that allows the user to set the database name.
|