PHP - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

PHP Create Database

PHP Create Database

shape Description

Till now creation of Database is done using PHPMyadmin directly.Now in PHP Create Database chapter,database creation though PHP is shown. In order to create database using MySQL and PHP mysql_query function is needed which accepts two parameters and TRUE is returned on success or FALSE on failure.

shape Example

MySQL Create DB - (MySQLi Object-oriented) [php] <!DOCTYPE html> <html> <body> <?php $HostName = "localhost"; $UserName = "root"; $Password = "password"; // Create connection $connection = new mysqli($HostName, $UserName, $Password); // Check connection if ($connection->connect_error) { die("Connection failed: " . $connection->connect_error); } // Create database $sql = "CREATE DATABASE accounts"; //The database name can be different also if ($connection->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $connection->error; } $connection->close(); ?> </body> </html> [/php] MySQLi Procedural [php] <!DOCTYPE html> <html> <body> <?php $HostName = "localhost"; $UserName = "root"; $Password = "password"; // Create connection $connection = mysqli_connect($HostName, $UserName, $Password); // Check connection if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } // Create database $sql = "CREATE DATABASE accounts"; if (mysqli_query($connection, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($connection); } mysqli_close($connection); ?> </body> </html> [/php]

Summary

shape Key Points

PHP Create Database figures out the following main points.
  • To create a database in MySQL using PHP requires mysql_query function.