Creation of Database & Table Through PHP

Introduction

Hi guys. In this article we are going to understand the MySQL database with PHP. A database is an organized collection of data for one or more purposes, usually in digital form. A database holds one or multiple tables.

Creation of database

Here in this section we will use the Create database statement to create the database.

Syntax

CREATE DATABASE database_name

Now we will focus on the creation of a database with PHP script. When using PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.

PHP script for creating database:

<html>
<
body bgcolor="Lightgreen">
<center>
<
h3> Creating a database <h3>
<
hr>
<?php
$con = mysql_connect("localhost","root","");
$db=
"Mike";
if (!$con)
  {
 
die('Could not connect: ' . mysql_error());
  }
if (mysql_query("CREATE DATABASE $db",$con))
  {
 
echo "Database created : $db";
  }
else
 
{
 
echo "Error creating database: " . mysql_error();
  }
mysql_close($con);
?>
</center>
</
body>
</
html>

Save it as abcd.php.

Output

To run the code, Open the XAMPP server and start the services like Apache and MySQL. Open the browser type: http://localhost/yourfoldername/abcd.php 

db1.gif
 

Once your database has been created, and if you hit the same URL again, the output will look as in the following:

db2.gif
 


Creation of Table

Here in this section we will create the table in a particular database. MySQL provides a variety of table types with varying levels of functionality. The CREATE TABLE statement is used to create a table in MySQL.

Syntax

CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type
)

Now we will focus on the creation of a table with a particular database with PHP script. The CREATE TABLE statement to the mysql_query() function to execute the command.

PHP script for creating database table:

<html>
<
body bgcolor="Lightgreen">
<center>
<
h3> Creating a database table <h3>
<
hr>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
 
die('Could not connect: ' . mysql_error());
  }
// Create database
if (mysql_query("CREATE DATABASE dwij",$con))
  {
 
echo "dwij Database created";
  }
else
 
{
 
echo "Error creating database: " . mysql_error();
  }
// Create table
mysql_select_db("dwij", $con);
$sql =
"CREATE TABLE PBL
(
FirstName varchar(15),
LastName varchar(15),
Age int
)"
;
// Execute query
mysql_query($sql,$con);
echo "PBL table created";
mysql_close($con);
?>
</center>
</
body>
</
html>

Save it as abcd.php.

Output

To run the code, Open the XAMPP server and start the services like Apache and MySQL. Open the browser type: http://localhost/yourfoldername/abcd.php 

db3.gif
 

Conclusion : With the help of the script shwn above we can execute each SQL statement of MySQL with a PHP script.

Thanks !


Similar Articles