Saturday, June 21

How to Select Data from MySql table using PHP


Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP function mysql_query.This tutorial will show you how to fetched data from mysql database.








Here i will create 2 php file and a Table under a Database:
  • connect.php // Database configuration file
  • select.php //  Contains PHP and HTML code and db selection code.
  • "selection" table in database "test" . 
Step 1 .
Create Mysql Database "test" and create table "insertion".
CREATE TABLE `test`.`insertion` (
`fname` VARCHAR( 50 ) NOT NULL ,
`lname` VARCHAR( 50 ) NOT NULL ,
`emailid` VARCHAR( 50 ) NOT NULL
) ENGINE = MYISAM ;


Now insert some data into this table. You can insert data in the table manually or you can insert data into table using PHP insertion code. If you don't know How to Insert Data into MySql table using PHP you can see this article here.

Step 2 .
Create Database configuration file : connect.php and write the bellow code.

<?php
$con=mysql_connect("localhost","root","");
if(!$con)
{
 die("Connection not Open".mysql_error());
}
mysql_Select_db("test",$con);
?>


Step 3 .
Create select.php and write the bellow code.

<html>
<head>
<title>Select</title>
</head>
<body>
<table align="center" border="1px" width="80%">
<tr><td>First Name</td><td>Last Name</td><td>Email ID</td></tr>
<?php
include("connect.php");
$sql='select * from   selection';
 $retval = mysql_query( $sql, $con );
  if(! $retval )
  {
    die('Could not get data: ' . mysql_error());
    
  }
  while($row = mysql_fetch_array($retval, MYSQL_NUM))
  {
   echo"<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td></tr>";
  }


?>

</table>
</body>
</html>


If you have any problem or further query  on this please comment. Thank you


1 comments so far

This comment has been removed by a blog administrator.