Posted in: PHP

PHP Create Database and Tables Dynamically Using MySQLi

Sometimes we forgot to create database and run our query than we got an error that is ” No Database with this name”. So I thought to figure it out and solve this issue by creating the database at the runtime if it is not available. If we do this we will never get this “No Database” error.

For doing this we will use our mysqli functions which is easy and very known for those who uses them. So lets get started.

Step 1. Define our database details

We will setup some variable so we will not write the details every time. We are using XAMPP at our end and we will do it over localhost.

After setting the database variables we will move to our next step.

Step 2. Try to connect with database

Now we will try to connect the database using mysqli_connect() with the above details.

If it will not connect than it will give us the error “error while connecting” otherwise it will connect. In next step we will check is is connected or not if not than what we can do.

Step 3. Check connection

For checking we will create an if else.

If it is connected it will echo the “connected” else it will echo the “Not Found”. Now if it is not connected than we will write some code to create the database.

Step3. Create the Object of mysqli to Create Database Dynamically

Now we will create the object of mysqli to create the database if it not connected.

By using this it will create the database with the name of “mydemo” or whatever you want to put.

Now we will connect this again so that we will use it. We will just call a line again which we previously called.

Step 4. Connect Again

Now if you try if else than you will see that it is connected because database is available and you will not get any error.

Step 5. Whole code at once

 Step 6. Now you can create tables.

You can create the tables now using the connection string.

Hope you like our tutorial for Create Database and Tables Using Mysqli connection string. If you have any issues than please comment below.


Leave a Reply

Your email address will not be published. Required fields are marked *