PHP : MySQL Create Table

Data is stored in the form of tables in the database. A table has its own unique name and consists of rows and columns.

Syntax:

CREATE TABLE table_name (column_name column_type);

Create Table using PHP and MySQL

<?php
/**
 * Create Database Connection
 */
 
$database_server = 'localhost';
$database_username = 'root';
$database_password = '';
$database_name = 'student';
 
// Create connection using mysqli_connect()
$conn = mysqli_connect($database_server, $database_username, $database_password, $database_name);
 
// If $conn is false, connection is failed
if (!$conn ) {
  die("Failed to connect to MySQL: " . mysqli_connect_error());
}
 
echo "Database Connected Successfully. <br />";
 
?>
<?php
/**
 * Create Database Table
 */
 
require_once('db-connection.php');
 
// Mysql query to create table
$mysql_query_statement = "CREATE TABLE users (
	id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
	name VARCHAR(30) NOT NULL,
	mobile VARCHAR(10) NOT NULL,
	email VARCHAR(50) NOT NULL UNIQUE
)";
 
if ($conn->query($mysql_query_statement) === TRUE) {
	echo "Table users created successfully.";
}
else {
	echo "Error creating table: " . $conn->error;
}
 
// Connection Close
mysqli_close($conn);
?>

In above example we have used 4th parameter for database_name in mysqli_connect() function. $conn->error return a error description string, if any error occurred.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.