PHPSuperBlog.com

Create MySQL database table with PHP

To create a MySQL database table with PHP is very straight forward, all you have to do is to know the query for creating a MySQL database table, and use PHP function mysql_query( ) to run that query. You could also use a HTML form to let the user to input the name of the table.

Here is an example I made to show you how to create a MySQL table:

First we have to connect to database.

mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");

Then we create a PHP variable to store the table name for the query to use. Why I show you in this example requires a PHP variable? This way, we could use a HTML form to let the user to input a name for the table and store it into this PHP variable.

$tablename = "atable";

Now we create the query for creating a table with 2 fields of varchar(20)

$query = "
CREATE TABLE $tablename (
field1 VARCHAR(20) NOT NULL ,
field2 VARCHAR(20) NOT NULL
)";

Then we run the query with the “mysql_query( )” PHP function and to check whether the table has created successfully, I have put an “if” condition statement there to echo out the result.

if(mysql_query($query)){
echo "table created";}
else{
echo "fail";}

All together we get:

<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
$tablename = "atable";
$query = "
CREATE TABLE $tablename (
field1 VARCHAR(20) NOT NULL ,
field2 VARCHAR(20) NOT NULL
)";
if(mysql_query($query)){
echo "table created";}
else{
echo "fail";}
?>
Share or Bookmark This Post...
  • Digg
  • Twitter
  • Technorati
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Live
  • MySpace
  • blogmarks
  • Gwar
  • MyShare
  • BarraPunto
  • laaik.it
  • Yahoo! Bookmarks
  • RSS
  • Reddit
  • Webnews.de

If you enjoyed this post, make sure you
Subscribe to my RSS feed!

Leave a Reply

You must be logged in to post a comment.


  • Categories

  • Useful Downloads