Php mysql create database if not exists

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.

<?php
// 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";
  }
}

mysql_close($link);
?>

Three steps to fix this:

  1. Don’t specify the database name when connecting.
  2. Your SQL statement should be CREATE DATABASE IF NOT EXISTS php1.
  3. Call mysqli_select_db($link, 'php1') to make that the default database for your connection.

Tags:

Mysql

Php