php - CREATE TABLE IF NOT EXISTS fails with table already exists -


i have following code:

$db_host = 'localhost'; $db_port = '3306'; $db_username = 'root'; $db_password = 'root'; $db_primarydatabase = 'dsl_ams';  // connect database, using predefined database variables in /assets/repository/mysql.php $dbconnection = new mysqli($db_host, $db_username, $db_password, $db_primarydatabase);  // if there errors (if no# of errors > 1), print out error , cancel loading page via exit(); if (mysqli_connect_errno()) {     printf("could not connect 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' exists

what don't understand is: isn't if not exists supposed cancel execution of sql query if table exists? in other words, if table exists, shouldn't exit if statement , not echo out @ all, , not attempt execute query?

just trying find best way "create table if doesn't exist" without outputting user.

try this

$query = "select id 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 see if in table , if returns null don't have table.

also there no boolean datatype in mysql, should int , set 1 or 0 when inserting table. don't need single quotes around everything, when hardcoding data query.

like this...

$query = "insert users (email, password, permission_level, application_completed, application_in_progress) values ('foobar@foobar.com', 'fjsdfbsjkbgs', 0, 0, 0)"; 

hope helps.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -