In this section, we will figure out how to make tables. Prior to making a table, first decide its name, field names, and field definitions.
Following is the overall language structure for table creation −
CREATE TABLE table_name (column_name column_type);
Audit the order applied to making a table in the PRODUCTS data set −
databaseproducts_ tbl(
product_id INT NOT NULL AUTO_INCREMENT,
product_name VARCHAR(100) NOT NULL,
product_manufacturer VARCHAR(40) NOT NULL,
submission_date DATE,
PRIMARY KEY ( product_id )
);
The above model uses "NOT NULL" as a field property to keep away from mistakes brought about by an invalid worth. The characteristic "AUTO_INCREMENT" trains MariaDB to increase the value of the ID field. The watchword essential key characterizes a section as the essential key. Numerous sections isolated by commas can characterize an essential key.
The two principle strategies for making tables are utilizing the order quick and a PHP content.
The Command Prompt
Use the CREATE TABLE order to play out the errand as demonstrated underneath −
root@host# mysql -u root -p
Enter password:*******
mysql> use PRODUCTS;
Database changed
mysql> CREATE TABLE products_tbl(
-> product_id INT NOT NULL AUTO_INCREMENT,
-> product_name VARCHAR(100) NOT NULL,
-> product_manufacturer VARCHAR(40) NOT NULL,
-> submission_date DATE,
-> PRIMARY KEY ( product_id )
-> );
mysql> SHOW TABLES;
+------------------------+
| PRODUCTS |
+------------------------+
| products_tbl |
+------------------------+
Guarantee all orders are ended with a semicolon.
PHP Create Table Script
PHP gives mysql_query() for table creation. Its subsequent contention contains the essential SQL order −
<html>
<head>
<title>Create a MariaDB Table</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ){
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = "CREATE TABLE products_tbl( ".
"product_id INT NOT NULL AUTO_INCREMENT, ".
"product_name VARCHAR(100) NOT NULL, ".
"product_manufacturer VARCHAR(40) NOT NULL, ".
"submission_date DATE, ".
"PRIMARY KEY ( product_id )); ";
mysql_select_db( 'PRODUCTS' );
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create table: ' . mysql_error());
}
echo "Table created successfully\n";
mysql_close($conn);
?>
</body>
</html>
On fruitful table creation, you will see the accompanying yield −
mysql> Table created successfully
