Complete Computer Knowledge Portal

Monday, December 9, 2013

Retrieving Data from MYSQL Database using PHP


Using these easy steps you can easily retrieve the data from MYSQL database. In this example I am assuming that you have already created MYSQL database and already contains some tabular data.
Create database named mydb
CREATE DATABASE `mydb`;

Create Table student on mydb Database:
Table info is created with three fields: id, name and Email Address. Id will be automatically incremented after every insert operation.
CREATE TABLE `mydb`.`student` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 100 ) NOT NULL ,
`contact_no` int( 20 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM

Insert some raw data for Accessing
INSERT INTO `mydb`.`student` (`id`, `name`, `contact_no`) VALUES (NULL, 'Dashmesh', '123456');
Create Database Connection (connection.php)
<?php
$host="localhost";
$username="your_db_username";
$password="your_db_password";
$db_name="mydb";
$con=mysql_connect("$host","$username","$password") or die("could not connect");
$db=mysql_select_db("$db_name")or die("cannot select DB");
?>

Now create a page that will retrieve data from Database(index.php)
<?php
include("connection.php");
$sql="SELECT * FROM student order by id";
$result=mysql_query($sql);
?>
<table width="525" border="1" align="center" cellpadding="3" cellspacing="1" bordercolor="#9933CC">
  <tr>
    <td colspan="10"><div align="center"><strong><font color="#000080" size="5"><b>Students
        List </b></font></strong></div></td>
  </tr>
  <tr align="center" valign="top">
    <td width="147"> <div align="center"><strong><font color="#000080" size="3.5">ID</font></strong></div></td>
    <td width="136"> <div align="center"><strong><font color="#000099">Name</font></strong></div></td>
    <td width="212"> <div align="center"><strong><font color="#000080" size="3.5">Contact
        No. </font></strong></div></td>
  </tr>
  <? while($rows=mysql_fetch_array($result)){
?>
  <tr align="center" valign="top">
    <td height="46"><? echo $rows['id']; ?> <div align="center"></div></td>
    <td><? echo $rows['name']; ?></td>
    <td><? echo $rows['contact_no']; ?></td>
  </tr>
  <?php
}
?>

Result so obtained will be as follows:

Students List
ID
Name
Contact No.
1
Dashmesh
123456

No comments:

Post a Comment