Friday, June 5, 2015

PHP with MySQL Database Example

INTRODUCTION

  • PHP is the acronym of Hypertext Preprocessor and also called Personal Home Page.
  • It is one of the server side scripting language which is mainly used Web Projects.
  • It is an open-source software used in many organizations.
  • An interpreter called “Zend Engine is also a free software.
  • The PHP codes can be embedded to HTML or HTML5 codes.
  • The syntax starts with <?php and ends with ?>
  • It supports object oriented programming.
In this post, we are going to learn how to connect MySQL using PHP and display data.

TOOLS & TECHNOLOGIES

  1. Eclipse Mars.2 with PHP Plugin
  2. WAMPSERVER 2.5
  3. MySQL 5

SETUP

  1. Open the \wamp\bin\apache\apache2.4.9\conf\httpd.conf file and update the port 8086.
Listen 0.0.0.0:8086
Listen [::0]:8086
  1. Start the WAMPSERVER and enter the URL http://localhost:8086/phpmyadmin/  in browser to check whether the server installed properly or not.

Follow the below steps to retrieve the data from MySQL using PHP.


Step 1 - Create a Database


Step 2 - Create a New User

Step 3 - Create a Table in MySQL

Create Query
CREATE TABLE IF NOT EXISTS `employee` (
 `empid` int(30) NOT NULL,
 `empname` varchar(30) NOT NULL,
 `address` varchar(40) NOT NULL
)

Insert Query
INSERT INTO `employee` (`empid`, `empname`, `address`) VALUES
(100, 'Ranjith', 'Chennai'),
(200, 'Bala', 'Bangalore'),
(300, 'Anbu', 'Delhi');

Step 4 -Create a PHP Project & a PHP File


Step 5 - Develop PHP Code to connect MySQL

EmployeeInfo.php
<?php
$dbUsername='scott';
$dbPassword='tiger';
$dbHost='localhost';
$databaseName='bank';

$connection = mysqli_connect($dbHost,$dbUsername,$dbPassword,$databaseName);

if($connection){
$query = "select * from employee";
$result = $connection->query($query);

if($result->num_rows >0){
while ($row = $result->fetch_assoc()) {
echo '<br> <b>Employee ID: </b>' . $row['empid'];
echo '<br> <b>Employee Name: </b>' .  $row['empname'];
echo  '<br> <b>Employee Address: </b>' . $row['address'];
echo  '<br>';
echo  '<br>';
}
}

}else{
die('Connection Error...' . mysqli_connect_error());
}

Step 6 - Run the Application

Right click the EmployeeInfo.php file in Eclipse and Run As 'PHP Web Application'.
In the URL, there is no port number displayed so it won't launch the application. Make below changes to overcome this issue.
Go to Preferences->PHP->PHP Servers->Edit->
Now again Run. The URL will be populated as http://localhost:8086//EmpInfo/EmployeeInfo.php

OUTPUT