Monday, August 27, 2012

Creating Database Tables:

To create tables in the new database you need to do the same thing as creating the database. First create the SQL query to create the tables then execute the query using mysql_query() function.

Example:

Try out following example to create a table:
<?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';
$sql = 'CREATE TABLE employee( '.
       'emp_id INT NOT NULL AUTO_INCREMENT, '.
       'emp_name VARCHAR(20) NOT NULL, '.
       'emp_address  VARCHAR(20) NOT NULL, '.
       'emp_salary   INT NOT NULL, '.
       'join_date    timestamp(14) NOT NULL, '.
       'primary key ( emp_id ))';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not create table: ' . mysql_error());
}
echo "Table employee created successfully\n";
mysql_close($conn);
?>
In case you need to create many tables then its better to create a text file first and put all the SQL commands in that text file and then load that file into $sql variable and excute those commands.
Consider the following content in sql_query.txt file
CREATE TABLE employee(
     emp_id INT NOT NULL AUTO_INCREMENT,
     emp_name VARCHAR(20) NOT NULL,
     emp_address  VARCHAR(20) NOT NULL,
     emp_salary   INT NOT NULL,
     join_date    timestamp(14) NOT NULL,
     primary key ( emp_id ));

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$query_file = 'sql_query.txt';

$fp    = fopen($query_file, 'r');
$sql = fread($fp, filesize($query_file));
fclose($fp); 

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not create table: ' . mysql_error());
}
echo "Table employee created successfully\n";
mysql_close($conn);
?>

No comments:

Post a Comment

Labels

AJAX (1) Answers (1) Apache (1) Array (16) bug (1) C (1) C++ (1) Calendar (1) Class (1) Commands (1) Cookies (2) Database (2) Date (7) Days (1) explode (1) File Upload (1) FILES (1) firewall (1) fix (1) Functions (26) GET (1) GMT (1) JavaScript (2) localhost (1) Mail (1) Menu (1) MYSQL (13) PERL (1) PHP (36) php.ini (1) POST (1) preg_match (1) Questions (1) Script (1) SMS (2) Solution (1) String (1) Time (5) Time Zone (1) Vista (1) Wamp Server (1) windows 7 (2) XML (1)

Popular Posts

Popular Posts