Sunday, 7 June 2015

PHP Mysql Connectivity

PHP Mysql Connectivity


Database connectivity with php code is very simple.
For this you have to write the following code.
Syntax-:

// creating connection
$con=mysql_connect(“localhost”,”root”,” ”) or die(“connection error”);
// selecting database
mysql_select_db(“database name”,$con) or die(“database error”);
In the above code in the first line mysql_connect() is a query which is used to create connection and accept three parameter .
  1. Host Name-(localhost)
  2. User Name-(root)
  3. Password-(which is blank on local server)

Note-The above code is for local server , if you use the actual server you have to use your database username and password. 

And in the second line mysql_select_db() is a query which is used to select the database and accept two parameter first is database name (required) and second is connection variable(optional).
Example-:
Here my database name is my_db and table name is my_tbl using this creating a program to insert data in the table my_tbl;
And suppose I have two field in the table name and age respectively.
<?php
$name="Satyam";
$age=12;
 
$con=mysql_connect(“localhost”,”root”,” ”) or die(“connection error”);
mysql_select_db(my_db,$con);

$q=mysql_query(“insert into my_tbl values(‘$name’,’$age’)”);

if($q)
{
echo “Record inserted successfully”;
}
else
{
echo “Error”.mysql_error();
}

?>