Create MySQL database table with PHP
Editor’s note:Â To create a MySQL database table with PHP is very straight forward, all you have to do is to know the query for creating the 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:
1 2 3 4 5 6 7 8 9 10 11 12 | 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";} |





Add A Comment