SQL PHP HTML ASP JavaScript articles and free scripts to download If you are facing any problem in viewing this page, please tell us
 

Creating tables by query


We can create new table by using sql. We have seen how to execute a query and get the records or modify the records in MySQL. Same way we can run one sql command to create tables. This can be a part of a script where based on the logic of the script we can design a table and create it.

We will start with simple create query for creating a new table.

$q="CREATE TABLE `sample_tb` (`empno` VARCHAR( 6 ) NOT NULL) ";

The above query will create a table sample_tb and add one column empno to it. But note that we have to execute the above code. After execution we can find out whether the query has successfully executed or not by using one if condition. If the query is not executed successfully then we will print the error message. If table create process is successful then we will display a success message. Here is the code

$q="CREATE TABLE `sample_tb` (`empno` VARCHAR( 6 ) NOT NULL) ";
$q1=mysql_query($q);
if($q1){echo "created table sample_tb....<br>";}
else{echo mysql_error();}

As you can see we have created the table, with one column to store the data. Now what happens if the table sample_tb already exists and we will try to create again? The system will generate an error message. So before trying to create the table we will delete the table and then create again. ( Note: do this if your requirement is there ). We also can't delete the table without checking the table is there or not. So we will use one if exists command like this.

$q="DROP table if exists sample_tb";
$q1=mysql_query($q);
if($q1){echo "deleted the table sample_tb....<br>";}
else{echo mysql_error();}

We can easily execute the create table query to generate the table. Note that this combination is used inside many scripts where temporary tables are create and deleted at the end.

Further readings
Creating a new table by using data from one table
Copying data from one table to another table
Updating another table with data from main table
Update SQL commands
Inserting SUM, AVG data from one table column to other using group by command
Create table query with if exists sql with php script
mobo03-12-2009
can you please tell me how can i copy a table from one user to another in mysqlplus.
Many thanks
Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked
Sections
PHP
JavaScript
ASP
HTML
SQL
Photoshop
Articles SEO
SQL Tutorial List
SQL Commands
SQL Sections
Date & Time
Join Table
String
Math
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.