Create a Table with PHP
One of the first few questions in my head when I first started programming in PHP was, How do I create a MySQL table (or two) from within my PHP script?
Of course, I have come a long way since then... and creating a MySQL table from within a PHP script is no longer a mystery to me.
However, browsing through a few popular PHP forums these last few days, I quickly realised that there are still a lot of webmasters who need to know how to get this done, and so I got to writing, as I usually do... ![]()
Assume you wanted to create an install page for a slammin' script you just wrote. One of the main things you would do in an PHP install script is to make PHP create the (MySQL) database tables needed for your script to work.
Create table: ZONES sample
If I had to create a MySQL table named `ZONES` in my script using PHP, this is what I'd do:
<?php
// Connect to our database
// ----------------------------------
// $conn = dbconnect();
$sql = 'CREATE TABLE `zones` (
`zid` TINYINT( 3 ) UNSIGNED NOT NULL AUTO_INCREMENT,
`zdesc` VARCHAR( 150 ) NOT NULL,
`zwidth` SMALLINT( 3 ) DEFAULT 0 NOT NULL,
`zheight` SMALLINT( 3 ) DEFAULT 0 NOT NULL,
`zmax` MEDIUMINT(7) unsigned NOT NULL default 12288,
PRIMARY KEY ( `zid` )
)';
echo 'Creating table: \'zones\'....';
mysql_query( $sql, $conn );
?>
That's all you have to do... and you can even do more than one database table creation in this one script / page, which is what I will show you below. Also, it's good idea to extend this script by checking if a table (name) being created is already existing in the database!
DROP before CREATE sample
In this example, I will create 2 tables, `zones` and `bcategory` (dropping or deleting any already existing table in the sample database first).
<?php
// Connect to our database
// ----------------------------------
// $conn = dbconnect();
$sql = 'DROP TABLE IF EXISTS `zones`';
mysql_query( $sql, $conn );
$sql = 'CREATE TABLE `zones` (
`zid` TINYINT( 3 ) UNSIGNED NOT NULL AUTO_INCREMENT,
`zdesc` VARCHAR( 150 ) NOT NULL,
`zwidth` SMALLINT( 3 ) DEFAULT 0 NOT NULL,
`zheight` SMALLINT( 3 ) DEFAULT 0 NOT NULL,
`zmax` MEDIUMINT(7) unsigned NOT NULL default 12288,
PRIMARY KEY ( `zid` )
)';
echo 'Creating table: \'zones\'....';
mysql_query( $sql, $conn );
$sql = 'DROP TABLE IF EXISTS `bcategory`';
mysql_query( $sql, $conn );
$sql = 'CREATE TABLE `bcategory` (
`bid` int(10) NOT NULL default 0,
`cid` int(10) NOT NULL default 0,
PRIMARY KEY ( `bid`, `cid` )
)';
echo 'Creating table: \'bcategory\'....';
mysql_query( $sql, $conn );
?>
