erdomester erdomester - 1 year ago 213
MySQL Question

Php mysql create database if not exists

I want to create a database. Why is not the db created with this code?

$dbname = 'regulations_db';
$con = mysql_connect("localhost","root","pass");
if (!$con)
die('Could not connect: ' . mysql_error());
if (mysql_num_rows(mysql_query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '". $dbname ."'"))) {
echo "Database $dbname already exists.";
else {
mysql_query("CREATE DATABASE '". $dbname ."'",$con);
echo "Database $dbname created.";

This is working, but I think the first one is the best practice:

if (mysql_query("CREATE DATABASE IF NOT EXISTS regulations_db",$con))
echo "Database created";
echo "Error creating database: " . mysql_error();

Answer Source

Just do a simple mysql_select_db() and if the result is false then proceed with the creation.

As an example, check out the first answer here by another very smart StackOverflower.

// Connect to MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());

// Make my_db the current database
$db_selected = mysql_select_db('my_db', $link);

if (!$db_selected) {
  // If we couldn't, then it either doesn't exist, or we can't see it.
  $sql = 'CREATE DATABASE my_db';

  if (mysql_query($sql, $link)) {
      echo "Database my_db created successfully\n";
  } else {
      echo 'Error creating database: ' . mysql_error() . "\n";

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download