Day 9: Database connectivity in PHP

Database is used to store information. In PHP we are using MySql as database server. Below are the steps to use MySql server with PHP:

Step 1 : Start MySql from your xampp panel.

step1

Step 2 : Open “http://localhost/phpmyadmin/” in browser.

Step 3 : Create new database in your localhost server (let’s take database name mydb).
step3
Step 4 : Crate a table in this database and insert some data with the help of below sql commands :

create table tbemp (id int primary key auto_increment, name varchar(45), salary int, city varchar(45));
insert into tbemp (name,salary,city) values (‘amit’,9000,’Chandigarh’);
insert into tbemp (name,salary,city) values (‘sumit’,9500,’Delhi’);

Writer the above Sql Commands in SQL tab of phpmyadmin and execute. After that table will created and data get inserted in your “tbemp” table. Now are going to write a program in PHP to display this data in browser.

Program 33: Handling database in PHP.

<?php
$host = “localhost”;
$user = “root”;
$password = “”;
$con = mysql_connect($host,$user,$password);
mysql_select_db(“mydb”,$con);
$query = “select * from tbemp”;
$data = mysql_query($query);
while($rec = mysql_fetch_array($data)) {
echo “Name : “.$rec[‘name’];
echo “<br>City : “.$rec[‘city’];
echo “<br>Salary : “.$rec[‘salary’];
echo “<hr>”;
}
?>

Explanation: mysql_connect function is use to open database server connection, we have passed 3 parameters in it host name, user name and password, by default host name is “localhost”, user name is “root” and password is “”. mysql_select_db is use the select the specific database from server. mysql_query function is used to execute sql query and mysql_fetch_array is used to fetch array from record set.


Program 34: Display data in table format.

<?php
$host = “localhost”;
$user = “root”;
$password = “”;
$con = mysql_connect($host,$user,$password);
mysql_select_db(“mydb”,$con);
$query = “select * from tbemp”;
$data = mysql_query($query);
?>
<html>
<body>
<table border=”1″ cellpadding=”5″>
<tr><th>Name</th><th>City</th><th>Salary</th></tr>
<?php
while($rec = mysql_fetch_array($data)) {
?>
<tr><td><?php echo $rec[‘name’];?> </td>
<td><?php echo $rec[‘city’];?> </td>
<td><?php echo $rec[‘salary’];?></td></tr>
<?php
}
?>
</table>
</body>
</html>

Output:
output


Comments

  1. By swth

Leave a Reply