Hello Friends,

If you are a learner (new) in PHP / Mysql and don’t know how to create table in Mysql database from php file than Here is the easiest and error-free way to create table in Mysql database.

<?php
///*** This file will help you to create table in database using PHP – Rakshit Patel **////

include(“mysql-connection.php”);

//** Creating databse **//

$sql = “CREATE DATABASE testing”;
$res = mysql_query($sql);

//** select database **//

mysql_select_db(‘testing’) or die(‘!! can not select database !!’);

//** Creating table **//

$sql = ‘CREATE TABLE test_table( ‘.
‘id INT NOT NULL AUTO_INCREMENT, ‘.
‘name VARCHAR(20) NOT NULL, ‘.
‘email VARCHAR(50) NOT NULL, ‘.
‘message TEXT NOT NULL, ‘.
‘PRIMARY KEY(id))’;

$res = mysql_query($sql);

////////// OR create table from file //////////////

$file = ‘tablename.txt’;

$fp = fopen($file, ‘r’); // open file in read mode
$sql = fread($fp, filesize($file)); // read file
fclose($fp); // clode file

$res = mysql_query($sql);

////////////////////////////////////

include(“mysql-connection-close.php”);
?>

Here first i have added mysql-connection.php file which will make connection with Mysql database. If you dont know how to make connection with Mysql database than click here.

You can create database by excuting query as per above or by just calling inbuilt function  mysql_create_db(“databasename”).

After successfully creating database , Select that database using inbuilt function mysql_select_db(“databasename”) to create tables in that database.

There are two ways to create table from PHP file. One is by executing query as per above.

Other is if you have .txt back up file of table than just open that file in read mode , read file and take the data in one variable and execute the query as i have written above.

At last i have included mysql-connection-close.php file.

<?php ///*** This file will close MYSQL connection using PHP – Rakshit Patel **//// 
mysql_close($connection); // close mysql connection
?>

This is nothing but it will close connection which we have made earlier. Its not necessary but a sign of Good Programmer.

Cheers !!

 

Related posts:

  1. Mysql Tutorial – Upload files to MYSQL database
  2. Mysql Tutorial – Download files from MYSQL database
  3. PHP Tutorial – Basic PHP variables
  4. Block IP addresses using .htaccess or .php file