PHP and MYSQL database connection and table creation only once if it does not already exist?


To create database only once, use the below syntax.

CREATE DATABASE IF NOT EXISTS yourDatabaseName;

To create table only once, use the below syntax −

CREATE TABLE IF NOT EXISTS yourTableName
(
   yourColumnName yourDatatype,
   .
   .
   .
   N
);

Let us implement both the above syntaxes to create database and table only once if does not already exist −

mysql> CREATE DATABASE IF NOT EXISTS login;
Query OK, 1 row affected (0.23 sec)

Above query creates a database successfully.

Following is the query to create a table −

mysql> CREATE TABLE IF NOT EXISTS DemoTable
(
   Id int
);
Query OK, 0 rows affected (0.56 sec)

Above query creates a table successfully.

Updated on: 30-Jul-2019

698 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements