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.

<?php
//connect to a database
$hostname="localhost";
$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:


<?php
//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';
CREATE TABLE 'web'  (
   `id` int UNIQUE NOT NULL,
   `name` varchar(40),
   `design` varchar(50),
   PRIMARY KEY(id)
);
INSERT INTO web VALUES(1,'php','nice');
INSERT INTO web VALUES(2,'js','good');
INSERT INTO web VALUES(3,'ajax','neat');

No comments:

Post a Comment