Tuesday, 2 July 2013

Coding to connect to MySQL database using PHP

Before you go to your MySQL database, you must know how to establish a connection to MySQL from inside a PHP script. This blog will help you to how to connect  your database easily.

//connect to a database
$username="Type your username";
$pass="Type your password";
$conn=mysql_connect($hostname,$username,$pass)or die (mysql_error());
echo 'connected to database';

Now you have connected to a database, then we have to select a database.Let's assume the database name is called 'codetruster'. To start working in this database, you'll need the mysql_select_db() function:

//select to a database
$seletc_db=mysql_select_db("codetruster",$conn) or die (mysql_error());
echo 'selected database';

Let's see the example to create 'codetruster' database  on your MySQL server. For that  you have to run the following script:

CREATE DATABASE 'codetruster';
   `id` int UNIQUE NOT NULL,
   `name` varchar(40),
   `design` varchar(50),
INSERT INTO web VALUES(1,'php','nice');
INSERT INTO web VALUES(2,'js','good');
INSERT INTO web VALUES(3,'ajax','neat');