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";
    }
    else
    {
        echo "Error creating database: " . mysql_error();
    }
                We can create a new database in MySQL by using the CREATE DATABASE statement with the below syntax: CREATE DATABASE [IF NOT EXISTS] database_name. [CHARACTER SET charset_name] [COLLATE collation_name];
CREATE DATABASE creates a database with the given name. To use this statement, you need the CREATE privilege for the database. CREATE SCHEMA is a synonym for CREATE DATABASE . An error occurs if the database exists and you did not specify IF NOT EXISTS .
The basic steps to create MySQL database using PHP are: Establish a connection to MySQL server from your PHP script as described in this article. If the connection is successful, write a SQL query to create a database and store it in a string variable. Execute the query.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With