Sie sind auf Seite 1von 5

Database Connectivity Using PHP

Once we have created the database and tables in MYSQL ,


the task left is to access and manipulated the data stored in
the tables.

Steps in Database Connectivity :

1.Connect to the server

First , of all we have to connect to the server MYSQL,


using the mysql_connect() command or function

The general form is ,

mysql_connect(“severname”,username,password);

(a) servername

It is used to specify the name of the server.

In our case it is "localhost"

(b) username

It is used to specify the name of the user


having access to the database .In our case it is root.

(c) password
It is used to specify the password given with
the username in our case it is blank.

e.g.

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

The $con will be treated as the connection object.

2. Select the database

Next you have to select the database on which you want


to manipulate the various operations.

For this purpose we have to make use of the


mysql_select_db();

The general form is ,

mysql_select_db("databasename",connectionobject);

e.g.

mysql_select_db("my_db", $con);

3. Specify the query


In this step you have to specify the sql statement on
the basis of the operation you want to
perform.

For this purpose you have to make use of


mysql_query() function

The general form is ,

mysql_query("sql query");

(a) Reteriving Record from the table

In this case you have to make used of SELECT


statement in the sql query.

e.g.
$result = mysql_query("SELECT *
FROM person");

$result will be considered as a recordset ,


which will store all the records
returned by the SQl select query.

Now we have to access the records row wise or


one record at a time.

e.g.

$row =
mysql_fetch_array($result)

mysql_fecth_array() will access one row from


the recordset at a time

$row will contain the entire record.

Now to access the particular field value

$row["fieldname"];

e.g.

echo $row['FirstName'] . " " .


$row['LastName'];

Q List all records from employee table in the ems


database.

<html>
<head>
<title>Using Database Connectivity</title>
</head>
<body bgcolor=cyan>
<?php
//connect to the server

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

//select the database


mysql_select_db("ems", $con);

//execute the query

$result=mysql_query("select * from employee");

//list all records

while($row=mysql_fetch_array($result))
{
echo "Employee Id :".$row["empid"]."<br>";
echo "Employee Name :".
$row["ename"]."<br>";
echo "Employee Salary :".
$row["esalary"]."<br><br>";
}
?>
</body>
</html>

Das könnte Ihnen auch gefallen