A piece of code that tries to connect to a database server with ADOdb library for PHP. If the database does not exist, the script tries to create it:
// example configuration:
$db_type = 'mysql';
$db_server = 'localhost';
$db_username = 'root';
$db_password = NULL;
$db_database = 'very_new_database';
$db_create = TRUE; // this variable sets
// This is needed to turn fatal errors to warnings when connecting.
// We use Connect for database checks, so this is really needed.
define('ADODB_ERROR_HANDLER_TYPE', E_USER_WARNING);
// include ADOdb class files:
require_once('adodb/adodb-errorhandler.inc.php');
require_once('adodb/adodb.inc.php');
// create connection object:
$db = ADONewConnection($db_type);
$db->debug = FALSE;
// first try to connect to the exact database on server
$ok = $db->Connect($db_server, $db_username, $db_password, $db_database);
// if failed to connect to database check if we should create it:
if (!$ok && $db_create) {
// failed db connection has to be constructed from start:
$db = ADONewConnection($db_type);
$db->debug = FALSE;
// try connecting without database parameter:
$ok = $db->Connect($db_server,
$db_username,
$db_password);
// if connected without database param:
if ($ok) {
// get SQL to create database:
$dict = NewDataDictionary($db);
$sql = $dict->CreateDatabase($db_database);
// try creating database:
// "2″ is status returned by ExecuteSQLArray()
if (!$ok = (2 == $dict->ExecuteSQLArray($sql))) {
// try to connect after creating:
$ok = $db->Connect($db_server, $db_username, $db_password, $db_database);
} else {
echo '<p>Failed to create database "'.$db_database.'".
The database server returned an error:
<em>'.$db->ErrorMsg().'</em>.</p>';
}
}
}
// Check status:
if ($ok) {
echo '<p>Connected successfully.</p>';
} else {
echo '<p>Database error: <em>'.$db->ErrorMsg().'</em></p>';
}