MySQLi Tutorial on MySQLi Create Database

create database using mysqladmin

you would need special privileges to create or to delete a mysql database. so assuming you have access to the root user, you can create any database using the mysql mysqladmin binary.

example

here is a simple example to create a database called tutorials

[root@host]# mysqladmin -u root -p create tutorials
enter password:******

this will create a mysql database called tutorials.

create a database using php script

php uses mysqli query() or mysql_query() function to create or delete a mysql database. this function takes two parameters and returns true on success or false on failure.

syntax

$mysqli→query($sql,$resultmode)

sr.no. parameter & description
1

$sql

required - sql query to create a mysql database.

2

$resultmode

optional - either the constant mysqli_use_result or mysqli_store_result depending on the desired behavior. by default, mysqli_store_result is used.

example

try the following example to create a database −

copy and paste the following example as mysql_example.php −

<html>
   <head><title>creating mysql database</title></head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass);
         
         if($mysqli→connect_errno ) {
            printf("connect failed: %s<br />", $mysqli→connect_error);
            exit();
         }
         printf('connected successfully.<br />');

         if ($mysqli→query("create database tutorials")) {
            printf("database tutorials created successfully.<br />");
         }
         if ($mysqli→errno) {
            printf("could not create database: %s<br />", $mysqli→error);
         }

         $mysqli→close();
      ?>
   </body>
</html>

output

access the mysql_example.php deployed on apache web server and verify the output.

connected successfully.
database tutorials created successfully.