PHP MySQL Create Table

PHP mysql_query() function is used to create table. Since PHP 5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2 alternatives.

  • mysqli_query()
  • PDO::__query()

PHP MySQLi Create Table Example

Example

<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$dbname = 'test';  
  
$conn = mysqli_connect($host, $user, $pass,$dbname);  
if(!$conn){  
  die('Could not connect: '.mysqli_connect_error());  
}  
echo 'Connected successfully<br/>';  
  
$sql = "create table emp5(id INT AUTO_INCREMENT,name VARCHAR(20) NOT NULL,  
emp_salary INT NOT NULL,primary key (id))";  
if(mysqli_query($conn, $sql)){  
 echo "Table emp5 created successfully";  
}else{  
echo "Could not create table: ". mysqli_error($conn);  
}  
  
mysqli_close($conn);  
?>  

Output:

Connected successfully
Table emp5 created successfully

PHP MySQL Connect

Since PHP 5.5, mysql_connect() extension is deprecated. Now it is recommended to use one of the 2 alternatives.

  • mysqli_connect()
  • PDO::__construct()

PHP mysqli_connect()

PHP mysqli_connect() function is used to connect with MySQL database. It returns resource if connection is established or null.Syntax

  1. resource mysqli_connect (server, username, password)  

PHP mysqli_close()

PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if connection is closed or false.

Syntax

  1. bool mysqli_close(resource $resource_link)  

PHP MySQL Connect Example

Example

<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$conn = mysqli_connect($host, $user, $pass);  
if(! $conn )  
{  
  die('Could not connect: ' . mysqli_error());  
}  
echo 'Connected successfully';  
mysqli_close($conn);  
?>  

Output:

Connected successfully