Creating Database and Tables in PHP

Estudies4you
Creating Database and Tables in PHP
Creating Database and Tables
  • Once connection is established, it is time to create database and tables to store values
  • You select a name for the database and create tables for that database
  • One can create and handle multiple databases using MySQL
Creation of Table Using PHP built-in functions
  • 'CREATE TABLE' is the statement used to create a database in MySQL
  • mysqli_query() function takes 'CREATE TABLE' as one of the argument to create a database.
  • The other argument for mysqli_query() is $dbhandle which is the return value of mysql_connect() function.
Example
<?php
$username = "xyz";
$hostname = "localhost";
$dbhandle = mysql_connect ($hostname,$username);
echo "connected to MYSQL";
$stmt="CREATE TABLE TEST TABLE S.NO INT,NAME CHAR(30))";
if(mysigli_query($dbhandle,$stmt))
{
echo" Table created successfully";
}
else
{
echo"error in table creation";
}

Creating Table in the Database
Tables can be created either through command prompt or by using phpMyadmin user interface.
In our example, the database 'test' is already created. You can now create the tables using the phpMyAdmin user interface. 
Creating Database and Tables in PHP

Steps to create a table using the user interface:
  1. Open the page http://localhost/phpmyadmin/
  2. Select the database from the list of databases created.
    • Note: If the created database is not found it can be created using the user interface.
  3. Click Create Table from the left panel.
  4. Type the table name and column names as required and click Save.
Adding values to the Table Using PHP built-in functions
  • The INSERT INTO statement is used to add new records to a database table. 
<?php
$username = "xyz";
$hostname = "localhost";
$dbhandle = mysqlconnect($hostname,$username);
echo "connected to MYSQL";
$stmt="INSERT INTO TEST TABLE VALUES(1,"Suhas")";
if(mysqliquery($dbhandle,$stmt))
{
echo" One row Inserted";
else
{
echo"error in INSERTION";
} !>
<?php
$username = "xyz";
$hostname = "localhost";
$dbhandle = mysqlconnect($hostname,$username);
echo "connected to MYSQL";
$stmt="CREATE TABLE TEST";
if(mysqliquery($dbhandle,$stmt))
{
  echo" Table created successfully";
}
else
{
echo"error in table creation";
}
              !>

Adding Values to the Table
Now, the table is created and values can be inserted using the Insert option.
Values will be inserted to the table once you click Go.
Creating Database and Tables in PHP



To Top