Integrate ICICI EazyPay payment gateway to your website

In this tutorial I would like to explain how to integrate Eazypay into your website.I am using Codeigniter to integrate eazypay.

Register and get you Merchant details through registration in ICICI Eazypay

To encrypt all parameter you can use eazypay inbuilt function of encryption.Please find below the code

function eazypayu_aes128Encrypt($plaintext,$key){
      $cipher = "AES-128-ECB";   
      if (in_array($cipher, openssl_get_cipher_methods())){
       $ivlen = openssl_cipher_iv_length($cipher);
       $iv = openssl_random_pseudo_bytes($ivlen);
       $ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv);
       return $ciphertext;
      }
}

To process your payment you have to take input from user and after thet serialize all data and set as parameter value.Below code is for reference.

public function make_payment() {
	$amount = $this->input->post('amount');
	$merchant_id = "YOUR MERCHANT ID";
	$key = "YOUR MERCHANT KEY";
	$reference_no = 2; 
	$sub_merchant_id = "YOUR SUBMERCHANT ID";
	$return_url = "YOUR REGISTERED RETURN URL";
	$paymode = "9";
	$mandatory_fields = $reference_no ."|".$sub_merchant_id ."|".$amount;
	$opt_fields = "";
	$e_sub_merchant_id = $this->eazypayu_aes128Encrypt($sub_merchant_id, $key);
	$e_reference_no = $this->eazypayu_aes128Encrypt($reference_no, $key);
	$e_amount = $this->eazypayu_aes128Encrypt($amount, $key);
	$e_return_url = $this->eazypayu_aes128Encrypt($return_url, $key);
	$e_paymode = $this->eazypayu_aes128Encrypt($paymode, $key);
	$e_mandatory_fields = $this->eazypayu_aes128Encrypt($mandatory_fields, $key);
	
	$redirect_url = 'https://eazypay.icicibank.com/EazyPG?merchantid='.$merchant_id.'&mandatory fields='.$e_mandatory_fields.'&optional fields='.$opt_fields.'&returnurl='.$e_return_url.'&Reference No='.$e_reference_no.'&submerchantid='.$e_sub_merchant_id.'&transaction amount='.$e_amt.'&paymode='.$e_paymode.'"';		

	redirect($redirect_url );
    		
}

After payment done you have to capture response getting from return URL. Here is the sample code to capture the response.

 public function success(){
        $res = $_REQUEST;
        $data_transaction = array(
        'Response_Code'=> $res['Response_Code'],
        'Unique_Ref_Number'=> $res['Unique_Ref_Number'],
        'Service_Tax_Amount'=> $res['Service_Tax_Amount'],
        'Processing_Fee_Amount'=> $res['Processing_Fee_Amount'],
        'Total_Amount'=> $res['Total_Amount'],
        'Transaction_Amount'=> $res['Transaction_Amount'],
        'Transaction_Date'=> date('Y-m-d',strtotime($res['Transaction_Date'])),
        'Interchange_Value'=> $res['Interchange_Value'],
        'TDR'=> $res['TDR'],
        'Payment_Mode'=> $res['Payment_Mode'],
        'SubMerchantId'=> $res['SubMerchantId'],
        'ReferenceNo'=> $res['ReferenceNo'],
        'ID'=> $res['ID'],
        'RS'=> $res['RS'],
        'TPS'=> $res['TPS'],
        'mandatory_fields'=> $res['mandatory_fields'],
        'optional_fields'=> $res['optional_fields'],
        'RSV'=> $res['Response_Code'],
        '_policy'=> $res['_policy'],
        'visitor'=> $res['visitor']
        );
        
        $this->db->insert('tbl_all_payments', $data_transaction);
        
        $this->load->view('success_page');
        
    }

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help! Stay tuned!

ASP.NET VS PHP: Side-by-Side Comparison

ASP.NET and PHP are popular languages in the programming world that are used by a large number of developers and make it difficult for new developers to choose one of them. Both of these languages are used in large web-based applications. Some successful companies like Google, Facebook and Twitter etc. also use these languages.

PHP

PHP stands for Hypertext Preprocessor. It is an open source programming language used for web development and can be embedded into HTML. The best part of PMP is that it is free and has a ton of frameworks, which simplifies web development and is simple even for beginners as it is simple and easy coding technique. PHP is great for professionals due to its advanced features.

Why use a PHP framework?

A PHP framework provides a basic structure to streamline the development of web apps. Applications and websites built using the PHP framework will help businesses improve their performance requirements.

The best PHP frameworks available:

  • Laravel
  • CodeIgniter
  • Symfony
  • Zend
  • Phalcon
  • CakePHP
  • Yii
  • FuelPHP

Demand for PHP Developer:

In Today’s web development market, most websites are developed using PHP development tools which indicates a huge demand for PHP developers. If you want to enter the IT world as a developer, PHP programming will be an easy entry point.

Getting PHP training from an authentic and reliable training provider will be a great platform to improve your skills.

ASP.NET

ASP.NET is an open-source server-side web development tool developed by Microsoft for easy creation of web applications and web pages. It can be written using any .Net supported language which makes it more popular among .NET developers. High speed and low cost are the main reasons for using it. A website built by ASP.NET is faster and more efficient than a website built with PHP.

Demand for ASP.NET Developer:

If you are a .NET developer, you will find yourself sought after by many asp.net development companies because your programming skills are extremely valuable in today’s market. There are many companies hunting for developers who can do programming with .NET. Therefore, it is advised that you brighten up your skills with ASP.NET certification training, which will increase your value manifold and have an edge over others. The ASP.NET certification training program will definitely make your future brighter and increase your career opportunities.

Comparison Between ASP.NET and PHP

Both the ASP.NET and PHP frameworks are effective frameworks to work with, however, there may be some advantages over the other. Let’s take a deeper look and compare these frameworks to understand which one is better than the other.

2. Market Share

According to the report, the underlying data source PHP is the most commonly used programming language with a 73% market share, with ASP.NET having a 23% market share. PHP has a 58% market share among the top 100K websites and PHP has a 52% market share among the 10K websites.

2. Websites

Here are two lists for comparing ASP.NET vs. PHP websites:

Websites built using PHPWebsites built using ASP.NET
Wikipedia
Facebook
Yahoo
WordPress.com
iStockPhoto
Microsoft
Dell
GoDaddy

3. Inbuilt features

PHP has many unique built in features that can help web developers. On the other side, ASP.NET has no such feature.

4. Speed and Performance

When you compare PHP vs. ASP.NET for speed, PHP will be the winner. ASP.NET is slightly slower than PHP because it is built on COM based systems whereas, the PHP program runs on its own memory space.

5. Community Support

Compared to ASP.NET, learning support is great in the PHP framework and has a large support community. It will be difficult for you to get hold of the #C language of ASP.NET as it is difficult to understand.

Key differences between ASP.NET vs PHP

PHPASP.NET
PHP was launched in 1995 by Rasmus Lerdorf.ASP.NET was launched by Microsoft in the year 2002.
PHP is Scripting languageASP.NET is a paid Microsoft provided web application framework.
PHP Suite for Small Size OrganizationsASP.NET is suitable for a large and medium sized organization.
PHP has a good market share in the marketASP.NET has more market share
PHP works slow for desktop applicationsASP.NET is well equipped to support and create desktop applications.
PHP is best suited for applications that have a core focus on the UIASP.NET is better for applications where the main concern is security.
easy to learnQuite challenging to learn.
PHP is easier to use than all other languagesCoding with ASP.NET is complicated
Since it uses built in memory space, PHP execution is fasterCoding with ASP.NET is complex
PHP can run on Linux operating system which is available for freeASP.NET requires a Windows platform that is not free

Conclusion

Both PHP and ASP.NET come with their pros and cons. PHP is safe, fast, reliable and inexpensive and ASP.NET is easy to use and maintain due to its class library system. Since both programming languages are similar and provide similar results, the company can make a choice based on the needs and requirements of the app they are about to develop.

PHP or Python: Which Language to Choose for Your Application

Intelligent applications are the best approach for a couple of years now – and this pattern is always developing. In any case, before beginning the procedure of web improvement for your expert site, progressed application or building and MVP of start-up thought, there would one say one is a question that should be replied… which programming language to pick?

Website designing and development improvement is a long separation run. You have to manage as a top priority coding at the customer side and server side, at that point choose Database innovation. For each progression, the decision of the specific programming language is essential, and you should decide before beginning the venture. There are a couple of approaches to analyze programming dialects, in any case, what probably concerns you is the financial limit, and after that – the ultimate result.

The Guido van Rossum developed Python in 1991. Python likewise has an open source foundation like PHP. Even though it offers a worked together web structure which upgrades its adaptability; however, it needs programming endeavor additionally, Zope application server is generally utilized python web system.

PHP development was started in 1994 by Rasmus Lerdorf. Prior the abbreviation utilized for PHP was Personal Home Page which was supplanted with Hypertext Pre-processor later. Its documentation is available online free of expense, as it is discharged as far as an open source permit. In the beginning, the PHP doesn’t bolster object-oriented programming, which was included later forms.

Which one suits you better PHP or Python?

PHP and Python share a ton practically speaking, and both are very ground-breaking with regards to web development, be that as it may, at last, you need to settle on a decision. How about we make it unmistakable, in best programming advancement firms you will discover developers for both languages. PHP is the center of by far most of the web applications while Python is increasing increasingly more group of spectators because of its readability and adaptability.

Python offers a wide range of frameworks that can perform similar functions as PHP Frameworks. Python is an excellent choice for the start-ups as it holds a small share of less than 1%. Based on the project if you are a start-up and you want to make it recognized quickly, Python is a better choice. Python seems easy to learn both languages are beginner friendly in comparison to C++ or other communications. Both are open source languages. Flask and Django are the two most used options that are used by the Python developers to develop the applications. On the other hand, PHP offers a large number of the framework that is used by the developers. Symfony and Laravel are the favored applications are used for the PHP.

Significant Differences in PHP and Python

While picking the best programming language for your business, it is imperative to consider the distinctive highlights:

  • The fundamental distinction between Python and PHP is their direction. PHP is item situated, and Python is aspect-oriented, which parts the program into various modules.
  • While working with Python, the designer can without much of a stretch, do separate modules and after that associate them on the “if-then” premise.
  • PHP development is less flexible than Python.
  • Python is more secure as compared to PHP
  • Python is readable that PHP as the commands used in Python is natural English language.
  • PHP requires libraries must be loaded manually, and Python uses special packages to load additional libraries.

Similarities between PHP and Python

  • Documentation

Both PHP and Python accompany detailed documentation that can enable you to out when you achieve an impasse. You need to investigate the documentation for the particular language, and, mainly, you’ll discover your answer for the issue.

  • Both languages are open source

Essentially, what this lets you know, is that you can get to the source code for both PHP and Python, along these lines giving you numerous conceivable outcomes for including new alternatives. You can change the language and improve it further to support different engineers, and yourself benefit from utilizing it.

  • Both have custom made IDEs for all operating system

When you achieve a higher level with any of the two languages, you can whenever download and introduce an IDE that will enable you to be significantly increasingly profitable.

Conclusion:

Even after comparing these two languages, it is certainly hard job to select one because both PHP and Python are great on their manner. Python is the gateway to teaching codes for machines. On the other hand, PHP is used for web development and server-side scripting.

PHP Web Services: How to Create a Simple Web Service Using PHP

A quick tutorial to explain what a Web Service is and how it can be used. Let see with step by step

What is Web Service ?

The main question arise before starting implementation of web services is what does mean by Web Service and What is the Web Service.Simply we can understand this Web Service by some definitions.

  • Web service is a client server application or application component for communication between client and server.
  • Web service is a software system for inter operable machine to machine communication..
  • Web service provide a common platform that allows to communicate between multiple applications with each other, which built on various programming languages.

Types of Web Services:

There are two types of web services.

1.) SOAP web services.

2.) RESTful web services.

SOAP Web Service:

SOAP stands for Simple Object Access Protocol. It is a XML-based protocol for accessing Web Services.

SOAP is XML based protocol known as platform independent and language independent. By using SOAP, you will be able to interact with other programming language applications.

RESTful Web Service(Also Known as REST API):

RESTful web service is based on representational state transfer (REST) technology. It is an architectural style and an approach for communication used in the development of Web Services.

Some Benefits of REST APIs:

  • REST APIs are fast.
  • No strict specification like SOAP.
  • Consumes less bandwidth and resource.
  • Language and Platform independent.
  • Can be written in any programming language.
  • Executed in any platform.
  • RESTful web services can use SOAP web services.
  • Permits different data format like Plain Text, HTML, XML and JSON.

Creating a Simple REST API:

I am going to create a simple REST API. In this API trying to get employee data based on search by employee id.To read this API i will use CURL method.

Create a form named Employees.php where an input box will get employee id from user.Please find below the code.

<!DOCTYPE html>
<html>
    <head>
        <title>Simple REST API</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </head>
    <body>
    <center>
    <?php
    if(!empty($result)){
        echo "<table>";
        echo "<tr><td>Employee ID:</td><td>$result->employeeid</td></tr>";
        echo "<tr><td>NAme:</td><td>$result->employeeName</td></tr>";
        echo "<tr><td>Age:</td><td>$result->employeeAge</td></tr>";
        echo "<tr><td>Salary:</td><td>$result->employeeSalary</td></tr>";
        echo "<tr><td>Response Code:</td><td>$result->responseCode</td></tr>";
        echo "</table>";
    }
    ?>
        <div class="container">
            <form action="" method="POST">
            <label>Enter Employee ID:</label><br />
            <input type="number" name="employee_id" placeholder="Enter Employee ID" required/>
            <br /><br />
            <button type="submit" name="submit">Submit</button>
            </form>
        </div>
    </center>
    </body>
</html>
In the same page we will put PHP script which will execute after form submitting.
<?php
if (isset($_POST['employee_id']) && $_POST['employee_id']!="") {
$employee_id = $_POST['employee_id'];
$url = "http://localhost/rest_api_example/api/".$employee_id;
$client = curl_init();
curl_setopt_array($client, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0
));
    $response = curl_exec($client);
$result = json_decode($response);
}
?>
Above script handling of API Call. Simply passing employee id through API and we will get the response.
Now, We will create the API named API.php where the write code to return employee data against employee id with response code.Please find below the API code.
<?php
header("Content-Type:application/json");
if (isset($_GET['employeeid']) && $_GET['employeeid']!="") {
include('./connection.php');
$db = new dbObj();
$con = $db->getConnstring();
$employeeid = $_GET['employeeid'];
$result = mysqli_query($con,
"SELECT * FROM `employee` WHERE id = $employeeid");
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_array($result);
$employeeName = $row['employee_name'];
$employeeAge = $row['employee_age'];
$employeeSalary = $row['employee_salary'];
$responseCode = 200;
response($employeeid, $employeeName, $employeeAge,$employeeSalary,$responseCode);
mysqli_close($con);
}else{
response(NULL, NULL, NULL,"No Record Found",200);
}
}else{
response(NULL, NULL, NULL,"Invalid Request",400);
}

function response($employeeid,$employeeName,$employeeAge,$employeeSalary,$responseCode){
$response = array(
      'employeeid' => $employeeid,
    'employeeName' => $employeeName,
    'employeeAge'=> $employeeAge,
    'employeeSalary' => $employeeSalary,
    'responseCode'=> $responseCode
    );
$json_response = json_encode($response);
echo $json_response;
}
?>

Clean URL through htaccess:

Clean URL also known as RESTful URL are user-friendly and do not contain a query string. Rather than they contain only the path of the resource.Please find below the code of htaccess.

RewriteEngine On # Turn on the rewriting engine
RewriteRule ^api/([0-9a-zA-Z_-]*)$ api.php?employeeid=$1 [NC,L]

Note: When you are testing this API example make sure CURL is enabled on your web server or on your localhost.

That’s all.Head to your browser and run this example.

Final Words:

This example simply getting employee data through an API, which can be used through calling that API and we will get all employee data as per required format like JSON, XML or Plain Text.
Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help. Stay tuned !

URLs Scrapper: How to Extract all URLs from a Web Page using PHP

It is sometimes required to extract all URLs from web page on demand.Lots of online tools are available to extract all URLs from a web page.This tutorial shows how to do that using PHP Script.This type of scrapper is may use to build sitemap generator or fetching Google result links.

To extract web URLs List from a web page I am going to use DOMdocument class of PHP. The DOM parser functions are part of the PHP core. No installation needed to use these functions.DOMDocument is very good at dealing with HTML as well as XML.In PHP, Just you need to create an instance of DOMDocument and initialize it, and set its version and character encoding.Let See how to do this.

<?php
$url = "https://techalltype.com/";
$html = file_get_contents($url);
$doc = new \DOMDocument('1.0', 'UTF-8'); /* instance of DOMDocument */
@$doc->loadHTML($html); /*The function parses the HTML contained in the string source */
$xpath = new \DOMXpath($doc); /*to retrieve selected html data */
$nodes = $xpath->query('//a');
foreach($nodes as $key => $node) {
echo $key++.".) ".$node->getAttribute('href')."<br/>";
}
?>

Here you can find more about on PHP DOMDocument.

​That’s All,thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion.

Google reCAPTCHA: Stop Bots using Google reCAPTCHA in PHP

Google reCaptcha is a free service from google that protect our website from spam and abuse.In this post I would like to show how we can integrate google recaptcha into our website. Let start with one by one.

1.) Get recaptcha setup keys from Google:

First of all you need site key and secret key from google console to use recaptcha into your website.To get keys Go to google console and fill all required details and you will get site and secret key.

Create Google Reccaptcha

After done with the fill up of required things, you will get site key and secret key.

Site and Secret key of google recaptcha

2.) Setup of reCAPTCHA with site and secret keys:

Next, You need to configure recaptcha into your website. Create a view file where you will show the captcha to the user.And in this file need to put data site key so that google recaptcha can authenticate with the site key.Here is how code looks.

Recaptcha.php

<!DOCTYPE html>
<html>
<head>
<title>Google reCAPTCHA Example</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<form method="post" action="process.php">
<center>
<legend>Google reCAPTCHA Example</legend><br>
First Name :<input type="text" name="fname"><br><br>
Last Name :<input type="text" name="lname"><br><br>
<div class="g-recaptcha" data-sitekey="Your site key"></div>
<input type="submit" name="submit">
</center>
</form>
</body>
</html>

3.) Validate reCAPTCHA in server side:

When your users submit the form where you integrated reCAPTCHA, you need to validate that user.

URL:-“https://www.google.com/recaptcha/api/siteverify?secret=”YOUR_SECRET_KEY”&response=”g-recaptcha-response”&remoteip=”UNIQUE_IP_OF_USER’s_SYSTEM”

Through above url you need to send the response to the google and google will verify that user.

Please find below the full code of recaptcha  server side validation.

process.php

<?php
if(isset($_POST['submit'])){

$secret = 'your secret key';
$response = $_POST['g-recaptcha-response'];
if(empty($response)){
echo "<script>alert('Please solve captcha !'); window.location = './recaptcha.php';</script>";
}
$ip = $_SERVER['REMOTE_ADDR'];
$dav = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$response."&remoteip=".$ip);
$res = json_decode($dav,true);
if($res['success']) {
echo "First Name :".$_POST['fname'].'<br>';
echo "Last Name :".$_POST['lname'];
} else {
echo "<script>alert('Please solve captcha !'); window.location = './recaptcha.php';</script>";
}
}
?>

That’s all. Now you can test it.

You may also like this Create captcha using Captcha helper in Codeigniter

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help!

Debugging PHP with Visual Studio Code

Debugging is one of the most important thing of our application development. To make quality software, debugging is a vital part of development.In this post, I am going to show how to debug PHP with visual studio code.

About Visual Studio Code:

Visual studio code, developed by microsoft is an open source code editor features integrated debugging for almost all programming language.

Installation of VS Code:

To get started first visit https://code.visualstudio.com to download visual studio code. Once VS code installed open it and then you need to install PHP debug extension.

Installation of Xdebug PHP Extension in VS Code:

To install PHP Extension just move to the extension in sidebar icons of VS code or you can press CTRL+SHIFT+X to explore extension. After that type PHP debug in search extension and install it.

Php Xdebug Extension

After successfully installed Extension you need to setup user setting. Just  Go to setting or press CTRL+, you will be move to the setting and change executable path as i am showing below.

Executable Path in VS code

Installation of Xdebug:

To configure xdebug in local server you need to go https://xdebug.org/wizard.php and paste here your phpinfo(). After that you will get instructions what to do next.To get phpinfo, go to the browser and type localhost you will be move to the dasboard and here you can find the phpinfo menu just click it and copy all the content by pressing CTRL+A.

INSTRUCTIONS

Xdebug extension

Debugging Setup in VS COde:

Next we need to setup debugging mode in vs code. Just open folder containing PHP Code file and choose the debug mode from the left hand side.

Debug option

Set Breakpoint:

To debug, need to add breakpoint in code. To add breakpoint click on the left of the line where you want to add breakpoint as i am showing showing below.

vscode breakpoint

Breakpoint are indicated by red dot. When execution start on browser, it will stop at breakpoint where we can check the state of the code and variables.

Start Debugging:

To start debugging just click on the start debugging option. For the first time it will create configuration file, no need to change for our puposes .If everything is setup correctly then VS code will be in debbuging mode. Run your page and you will get your debugging environment in VS code with Xdebug.

Xdebug Test

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. If you face any issue with this code let us know. We’d love to help!

Insert, Edit, Update, Delete Data using Php

In order to insert, edit, update Data in Php, We need to follow certain steps:-

  1. Check the connection to database.
  2. Create an html Form
  3. Insert data to database by filling form
  4. Edit, Update, Delete Data.

Check the connection to database.

In order to check connection to database, we need to know SERVER NAME, USER, PASSWORD, DATABASE .

db.php

<?php
ob_start();
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'techalltype');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
?>

NOTE:- While working on local computer server name is localhost, username is root,and password is blank (by default).

Create an html Form:-

In this step we simply use html to create a form.

index.php

<form action="insert.php" method="post">
<p>
  <label> USER NAME : </label>
  <input type="text" name="username" required placeholder="Enter your name" />
</p>
<p>
  <label> EMAIL ID : </label>
  <input type="email" name="usermail" required placeholder="Enter your Email ID"/>
</p>
<p>
  <label> MOBILE NUMBER : </label>
  <input type="text" name="usermobile" required placeholder="Enter your mobile number"  />
</p>
<p>
  <input type="submit" name="send" value="Submit" />
</p>
</form>

Here action=”insert.php”  means when we click on submit button the page will redirect to insert.php page. Method=”post” means when form will submit form will use post data.(Post data is referred most times because post method can carry maximum data from one page to another).

Insert.php

<?php
 ob_start();
  include("db.php");  // check the connection
  if(isset($_POST['send'])!="") // if send button is clicked
  {
  $username=mysql_real_escape_string($_POST['username']);  // mysql_real_escape_string use to escapes special characters in a string
  $usermail=mysql_real_escape_string($_POST['usermail']);
  $usermobile=mysql_real_escape_string($_POST['usermobile']);
  $update=mysql_query("INSERT INTO register(username,emailid,mobileno,created)VALUES
									  ('$username','$usermail','$usermobile',now())"); // insert statement to add data to database
  
  if($update)
  {
	  $msg="Successfully Updated!!";
	  echo "<script type='text/javascript'>alert('$msg');</script>";// If data inserted to database alert message display
	  header('Location:index.php');// If data inserted move to index.php page 
  }
  else
  {
	 $errormsg="Something went wrong, Try again"; 
	  echo "<script type='text/javascript'>alert('$errormsg');</script>"; // if data not inserted up line message display
	  header('Location:index.php'); If data not inserted move to index.php page 
  }
  }
 ob_end_flush();
?>

Display data from database:-

To view data from database, we need to create a page

view.php

<?php
 include('db.php');
  $select=mysql_query("SELECT * FROM register order by id desc"); // select * means display all records 
  $i=1;
  while($userrow=mysql_fetch_array($select))
  
  {
  $id=$userrow['id'];
  $username=$userrow['username'];
  $usermail=$userrow['emailid'];
  $usermobile=$userrow['mobileno'];
  $created=$userrow['created']
?>

 <p> USER NAME : <span><?php echo $username; ?></span>
    <a href="delete.php?id=<?php echo $id; ?>" 
    onclick="return confirm('Are you sure you wish to delete this Record?');">
    		<span class="delete" title="Delete"> delete </span></a>
  </p>
  <br />
  <p> EMAIL ID : <span><?php echo $usermail; ?></span>
    <a href="edit.php?id=<?php echo $id; ?>"><span class="edit" title="Edit"> edit </span></a>
  </p>
  <br />
  <p> MOBILE NO : <span><?php echo $usermobile; ?></span>
  </p>
<br>
<?php } ?>

Edit data-

In order to edit data from database we need to click on edit button available on view.php.

edit.php

<?php 
ob_start();
include('db.php');
if(isset($_GET['id']))
{
  $id=$_GET['id'];
  if(isset($_POST['update']))
  {
  $eusername=$_POST['eusername'];
  $eusermail=$_POST['eusermail'];
  $emobile=$_POST['eusermobile'];
  $updated=mysql_query("UPDATE register SET 
		username='$eusername', emailid='$eusermail', mobileno='$emobile' WHERE id='$id'")or die();
  if($updated)
  {
  $msg="Successfully Updated!!";
  header('Location:index.php');
  }
}
}
ob_end_flush();
?>


<?php 
  if(isset($_GET['id']))
  {
  $id=$_GET['id'];
  $getselect=mysql_query("SELECT * FROM register WHERE id='$id'");
  while($profile=mysql_fetch_array($getselect))
  {
    $username=$profile['username'];
    $usermail=$profile['emailid'];
    $usermobile=$profile['mobileno'];
?>

<form action="" method="post">
    <p>
      <label> USER NAME : </label>
      <input type="text" name="eusername" required placeholder="Enter your name" 
      value="<?php echo $username; ?>" id="inputid" />  // calling data from database in textbox and by submitting the form updated data insert in database
    </p>
    <p>
      <label> EMAIL ID : </label>
      <input type="email" name="eusermail" required placeholder="Enter your Email" 
      value="<?php echo $usermail; ?>" id="inputid" />
    </p>
    <p>
      <label> MOBILE NUMBER : </label>
      <input type="text" name="eusermobile" required placeholder="Enter your mobile number" 
      value="<?php echo $usermobile; ?>" id="inputid" />
    </p>
    <p>
      <input type="submit" name="update" value="Update" id="inputid" />
    </p>
  </form>

<?php } } ?>

Delete data-

In order to delete data from database using form we make page

delete.php

<?php
  ob_start();
  include("db.php");
  if(isset($_GET['id'])!="")
  {
  $delete=$_GET['id'];
  $delete=mysql_query("DELETE FROM register WHERE id='$delete'");
  if($delete)
  {
	  header("Location:index.php");
  }
  else
  {
	  echo mysql_error();
  }
  }
  ob_end_flush();
?>

Register.sql

CREATE TABLE IF NOT EXISTS `register` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(500) NOT NULL,
  `emailid` varchar(500) NOT NULL,
  `mobileno` varchar(500) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

 

 

 

 

Apache Server not running in Localhost

Why I’m facing this problem?

Generally, Apache and MySQL run without any problem, but in some situation Apache not started, this is because of just one reason and that is Port number. If any software installed before Xampp/Wamp installation take the default port (Port No. 80) than this problem came into existence.

Steps to resolve Apache not working?

In order to solve this problem you just have to follow some simple steps:-
  1. Open the Xampp/Wamp Control Panel, look for Apache, there is a config button click on it. Look for option Apache (httpd.config).
  2. click on (httpd.config) that open in notepad and then click CTRL+F key  a popup window appear. Write 80 in text-box and click find next button.
  3. Replace/Change 80 to 786 (ex-786 we can take another number also), repeat this process till cannot find 80 pop windowappear (3 time).
  4. Save the file and close.
  5. Then, in control panel we look for config button which is at top right side of control panel. Click on button a pop up window appear Configuration of Control Panel here we select Service and Port Settings another pop up window appear name Service Settings here at main port 80 is default change to 786. Click save button in Service Settings, and Configuration of Control Panel.
  6. Press start button of Apache.
  7. Go to web browser (ex- chrome), click on  address bar, write localhost:786  locacalhost:786/dashboard/ in address bar appear and dashboard opens.

How to get Time ago and Days left using Php script

Here i am going to show how to get time ago details and days left details using php script.Time ago is for that activity time, which has been done some time before and the days left function is for that activity time, which is still pending. Here is the how both codes looks.

1.) Time ago function.

function timeAgo($timeAgo)
{
$timeAgo = strtotime($timeAgo);
$curTime = time();
$timeElapsed = $curTime - $timeAgo;
$seconds = $timeElapsed;
$minutes = round($timeElapsed / 60);
$hours = round($timeElapsed / 3600);
$days = round($timeElapsed / 86400);
$weeks = round($timeElapsed / 604800);
$months = round($timeElapsed / 2600640);
$years = round($timeElapsed / 31207680);
/* Seconds&nbsp; Calculation*/
if ($seconds &lt;=60) {
return'Just Now';
} /* Minutes */
elseif ($minutes &lt;=60) {
if ($minutes ==1) {
return"One Minute ago";
} else {
return $minutes." time ago minutes";
}
} /* Hours */
elseif ($hours &lt;=24) {
if ($hours ==1) {
return"One hour ago";
} else {
return $hours." Hour Ago";
}
} /* Days */
elseif ($days &lt;=7) {
if ($days ==1) {
return"One day ago";
} else {
return $days." days ago";
}
} /* Weeks */
elseif ($weeks &lt;=4.3) {
if ($weeks ==1) {
return"One week ago";
} else {
return $weeks." week ago";
}
} /* Months */
elseif ($months &lt;=12) {
if ($months ==1) {
return"One month ago";
} else {
return $months." month ago";
}
} /* Years */
else {
if ($years ==1) {
return"One year ago";
} else {
return $years." year ago";
}
}
}
2.) Days left function.
function daysleft($time)
{
$result = null;
$toDate = strtotime($time);&nbsp; /*Future date*/.
$curDate = strtotime(date('Y-m-d'));
$timeleft = $toDate - $curDate;
$daysleft = round((($timeleft / 24) / 60) / 60);
if ($daysleft ==1) {
$result = $daysleft . ' ' . "Day" . ' ' . "left";
} else if ($daysleft &gt; 1) {
$result = $daysleft . ' ' . "Day" . ' ' . "left";
} else if ($daysleft == -1) {
$result = $daysleft . ' ' . "Day" . ' ' . "Gone";
} else if ($daysleft &gt; -1) {
$result = $daysleft . ' ' . "Day" . ' ' . "Gone";
}
return $result;
}
Note: Set date_default_timezone_set() before you using both functions so that you will get correct time information.
Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion and problems if you face – let us know. We’d love to help!