Tuesday, October 27, 2009

Code to connect PHP and MySQL

Program to start database connection:

$con = mysql_connect("localhost","root","root");
echo "connected";
if (!$con)
{
die('Could not connect: ' . mysql_error());
}


Program to create database and create table:

// create connection
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// Create database
if (mysql_query("CREATE DATABASE employee",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}

// Create table
mysql_select_db("employee", $con);
$sql = "CREATE TABLE emp
(
ename varchar(15),
eno int,
age int
)";

// Execute query
mysql_query($sql,$con);
mysql_close($con);


Program to insert values to table:

// create connection
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// select database
mysql_select_db("employee", $con);

mysql_query("INSERT INTO emp (ename,eno,age)
VALUES ('Sam', '1001', '24')");

mysql_query("INSERT INTO emp (ename,eno,age)
VALUES ('Sunil', '1002', '32')");

mysql_close($con);

No comments:

Post a Comment