Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CREATE TABLE IF NOT EXISTS fails with table already exists [duplicate]

I have the following code:

$db_host = 'localhost';
$db_port = '3306';
$db_username = 'root';
$db_password = 'root';
$db_primaryDatabase = 'dsl_ams';

// Connect to the database, using the predefined database variables in /assets/repository/mysql.php
$dbConnection = new mysqli($db_host, $db_username, $db_password, $db_primaryDatabase);

// If there are errors (if the no# of errors is > 1), print out the error and cancel loading the page via exit();
if (mysqli_connect_errno()) {
    printf("Could not connect to MySQL databse: %s\n", mysqli_connect_error());
    exit();
}

$queryCreateUsersTable = "CREATE TABLE IF NOT EXISTS `USERS` (
    `ID` int(11) unsigned NOT NULL auto_increment,
    `EMAIL` varchar(255) NOT NULL default '',
    `PASSWORD` varchar(255) NOT NULL default '',
    `PERMISSION_LEVEL` tinyint(1) unsigned NOT NULL default '1',
    `APPLICATION_COMPLETED` boolean NOT NULL default '0',
    `APPLICATION_IN_PROGRESS` boolean NOT NULL default '0',
    PRIMARY KEY  (`ID`)
)";

if(!$dbConnection->query($queryCreateUsersTable)){
    echo "Table creation failed: (" . $dbConnection->errno . ") " . $dbConnection->error;
}

Which outputs...

Table creation failed: (1050) Table '`dsl_ams`.`USERS`' already exists

What I don't understand is: isn't IF NOT EXISTS supposed to cancel the execution of the SQL query if that table already exists? In other words, if the table exists, shouldn't it exit that if statement and not echo anything out at all, and not attempt to execute the query?

Just trying to find the best way to "create a table if it doesn't exist" without outputting anything to the user.

like image 928
Samuel Stiles Avatar asked May 14 '13 23:05

Samuel Stiles


People also ask

Do not CREATE TABLE if already exists?

The “CREATE TABLE if not exists” statement is very useful in creating a table because it will not create the table if the table of the same name already exists in the database.

Does CREATE TABLE overwrite existing table?

No. In general you have to DROP the table first before CREATE succeeds. There are lots of exceptions to this when it comes to actual implementations, such as if the table is temporary or permanent, access rights where multiple users can have the same table name as long as they all use different user names.

What happens if you create a table that already exists?

When you try to create a table with an already existing table name, you will receive an error message, and no table will be modified or created.


2 Answers

Try this

$query = "SELECT ID FROM USERS";
$result = mysqli_query($dbConnection, $query);

if(empty($result)) {
                $query = "CREATE TABLE USERS (
                          ID int(11) AUTO_INCREMENT,
                          EMAIL varchar(255) NOT NULL,
                          PASSWORD varchar(255) NOT NULL,
                          PERMISSION_LEVEL int,
                          APPLICATION_COMPLETED int,
                          APPLICATION_IN_PROGRESS int,
                          PRIMARY KEY  (ID)
                          )";
                $result = mysqli_query($dbConnection, $query);
}

This checks to see if anything is in the table and if it returns NULL you don't have a table.

Also there is no BOOLEAN datatype in mysql, you should INT and just set it to 1 or 0 when inserting into the table. You also don't need single quotes around everything, just when you are hardcoding data into the query.

Like this...

$query = "INSERT INTO USERS (EMAIL, PASSWORD, PERMISSION_LEVEL, APPLICATION_COMPLETED, APPLICATION_IN_PROGRESS) VALUES ('[email protected]', 'fjsdfbsjkbgs', 0, 0, 0)";
like image 156
Josh Balcitis Avatar answered Oct 05 '22 13:10

Josh Balcitis


To avoid outputting anything, test for the table in your php before trying to create the table. For example,

$querycheck='SELECT 1 FROM `USERS`';

$query_result=$dbConnection->query($querycheck);

if ($query_result !== FALSE)
{
 // table exists
} else
{
// table does not exist, create here.
}
like image 29
Eduardo Vieira Avatar answered Oct 05 '22 15:10

Eduardo Vieira