$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
$query="CREATE TABLE `sample_tb` (`empno` VARCHAR( 6 ) NOT NULL) ";
if ($connection->query($query)) {
echo "created table sample_tb....";
}else{
echo $connection->error;
}
Table 'sample_tb' already exists
To avoid error , use IF NOT EXISTS
CREATE TABLE IF NOT EXISTS `sample_tb` (`empno` VARCHAR( 6 ) NOT NULL)
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.
$query="DROP table IF EXISTS sample_tb";
if ($connection->query($query)) {
echo "Table sample_tb deleted ....";
}else{
echo $connection->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.
if($stmt = $connection->query("SHOW TABLES LIKE 'sample_tb' ")){
if($stmt->num_rows ==1 ){
echo "table is created ";
}else{
echo $connection->error;
}
}
CREATE TABLE `student` (
`id` int(2) NOT NULL,
`name` varchar(50) CHARACTER SET utf8 NOT NULL DEFAULT '',
`class` varchar(10) CHARACTER SET utf8 NOT NULL DEFAULT '',
`mark` int(3) NOT NULL DEFAULT '0',
`gender` varchar(6) CHARACTER SET utf8 NOT NULL DEFAULT 'male',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
SQL References
Alter Tablemobo | 03-12-2009 |
can you please tell me how can i copy a table from one user to another in mysqlplus. Many thanks |
dan | 02-06-2012 |
Thank you very very much! |