Board index   FAQ   Search  
Register  Login
Board index PHP PHP General

check the condition before creating the table

General discussions related to php

Moderators: macek, egami, gesf

check the condition before creating the table

Postby Gamers » Mon Jun 11, 2012 9:31 am

Hi All,

This is my first post into this forum, let me describe my problem, actually i want to create a table with condition checks, eg if the table is already exit into the database i will get the error , if the table doesnt exit into the database then the table is created and the message will be display,

table human2 is already exit into the database sample, but how could i check if table exits into the database.


<html>

<body bgcolor="lavender">

<?php

//Connect to our localhost using username and password

$con = mysql_connect("localhost","root","");

//Checking connection query

if (!$con)
{

die('Could not connect Database Server : ' .mysql_error());

}

$database=sample;

$check=mysql_select_db("$database",$con);

$table=human2;

if (!$check)
{
die('cant select the database : ' .mysql_error());
}

elseif($check==1)
{

$maketab="CREATE TABLE $table(FirstName varchar(15),LastName varchar(15),Age int)";

//Execute the query

mysql_query($maketab,$con);

echo "tables $table is created ";

}

elseif($maketab==0)

{
echo "Cant create a table ".mysql_error();
}
//Close the my sql connection
mysql_close($con);

?>
Gamers
New php-forum User
New php-forum User
 
Posts: 48
Joined: Mon Jun 11, 2012 9:13 am

Re: check the condition before creating the table

Postby ejsexton82 » Tue Jun 12, 2012 3:02 am

Add "IF NOT EXISTS" to your MySQL statement:

Code: Select all
CREATE TABLE IF NOT EXISTS human2(FirstName varchar(15),LastName varchar(15),Age int)
User avatar
ejsexton82
New php-forum User
New php-forum User
 
Posts: 86
Joined: Mon Jun 04, 2012 10:05 pm
Location: Ankara, Turkey

Re: check the condition before creating the table

Postby Gamers » Tue Jun 12, 2012 4:09 am

Thanks for your reply,

i made a amendment into my script, and its working now

$check=mysql_select_db("$database",$con);

$table=human6;

$checktb="SELECT * FROM $table";
$result=mysql_query($checktb);
if (!$check)
{
die ('Could not connect to Database ' .mysql_error());
}
elseif (!$result)
{

$maketab="CREATE TABLE $table(FirstName varchar(15),LastName varchar(15),Age int)";

mysql_query($maketab,$con);

echo "<b>Table $table is created Successfully</b>";

}

else
{
echo "<h1><i><center>Table $table is already exits in the $database database</i></center>" ;
}

//Close the my sql connection
mysql_close($con);

?>
Gamers
New php-forum User
New php-forum User
 
Posts: 48
Joined: Mon Jun 11, 2012 9:13 am


Return to PHP General

Who is online

Users browsing this forum: Majestic-12 [Bot] and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.