SOAP web service using PHP + Mysql


Introduction:

This post for people those who are facing trouble with my last article “How to create SOAP service?”. These days web service is playing vital role in most of the web or mobile based application, where cross platform application used to connect and share data using web service. I will explain with some simple steps to do this stuff.

Download


Step 1:

Create a server page called soap_server.php into http://localhost/soapserver/. Paste the below code into the soap_server.php file.



// nosoap.php library file inside your lib/ directory
require_once('lib/nusoap.php');

$server = new nusoap_server;

/*
$server->configureWSDL('server', 'urn:server');
$server->wsdl->schemaTargetNamespace = 'urn:server';
$server->register('mypollServer', 
  array('value' => 'xsd:string'), array(
        'return' => 'xsd:string'), 'urn:server', 
        'urn:server#mypollServer
'
  );
*/

//register a function that works on server
 $server->register('getInfo');

 // create age calculation function
 function find_age($birthday)
 { 
    list($byear, $bmonth, $bday) = explode('-', $birthday);
   list($cyear, $cmonth, $cday) = explode('-', date('Y-m-d'));
 
   $cday -= $bday;
   $cmonth -= $bmonth;
   $cyear -= $byear;
 
   if($cday < 0)
   $cmonth--;
   if($cmonth < 0)
   $cyear--;
 
   return $cyear;
 }

 // create the function 
 function getInfo($name, $birthday)
 {
    $result['status'] = true;

    if(!$name){
      return new soap_fault('Client','','SANJAY!');
    }


    // Return if you want only very few server response else delete this line.
    //return $result = array('name'=> $name,'age'=> find_age($birthday) );

    

    $conn = mysql_connect('localhost','root','');
    mysql_select_db('webservice', $conn);

    $sql = "SELECT * FROM books";
    $q = mysql_query($sql);

    $result = array();

    while($row = mysql_fetch_array($q)) {

       $result[] = array(
                    'cd'=>$row['cd'],
                    'title'=>$row['title'],
                    'author'=>$row['author'],
                    'publisher'=>$row['publisher']
        );

    }

   return $result;
 }

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server ->service($HTTP_RAW_POST_DATA);
exit();



Step 2:

Now let us create a page called soap_client.php and paste below code to call soap server.



require_once('lib/nusoap.php');
header('Content-type: text/html');

$client = new nusoap_client('http://localhost/soapserver/soap_server.php');
$err = $client->getError();

if ($err) {
 echo '

Constructor error

' . $err . '

';exit; } $param = array( 'name' => 'Sanjoy Dey','birthday'=>'1987-12-20'); $response = $client->call('getInfo',$param); var_dump($response); if($client->fault) { echo "FAULT: Code: (".$client->faultcode.") "; echo "String: ".$client->faultstring; } else { echo $response['name']."\n Age: ".$response['age']."'s"; } echo '<h2> Request</h2> <>' . htmlspecialchars($client-&gt;request, ENT_QUOTES) . '</br> '; echo '<h2> Response</h2> <br>' . htmlspecialchars($client-&gt;response, ENT_QUOTES) . '</br> '; //echo '<h2>Debug</h2><br>' . htmlspecialchars($client-&gt;debug_str, ENT_QUOTES) . '</br>';

Step 3:

Go to browser and run http://localhost/soapserver/soap_client.php file. You will Soap Response as "Name" and "Date of Birth".

Conclusion:

This small post help you to create basic SOAP web service using PHP and nusoap.php library. Hope this post helps to solve displaying blank page. Keep visiting and stay updated. You can also join our technical groups by clicking below links.

Good Luck!

How to write SOAP web service using PHP?


In my previous post i have explained "How to read gmail inbox using PHP". Today I am going to write on Web service using SOAP. If you are a newbie and have a question in mind that "How to create a SOAP service?" this article will be useful to get started. Here are few easy steps to follow.

[NB: If you are facing trouble with below code then please do visit my latest updated post "SOAP web service using PHP". ]

Step 1 :

Download nusoap library file from here. Unzip and copy the folder into www (WAMP) root folder. If you are using Xampp tool paste it into htdocs/xampp/ folder.

Step 2 :

Now lets create two php file one is server.php and another client.php.

Step 3 :

Copy below snippet into your server.php.

 
     require_once('lib/nusoap.php');
 $server = new nusoap_server;
/*
//require("Connection.class.php"); 
$server ->configureWSDL('server', 'urn:server');
$server ->wsdl->schemaTargetNamespace = 'urn:server';
$server ->register('mpollServer', array('value' => 'xsd:string'), 
                    array('return' => 'xsd:string'), 'urn:server', 'urn:server#mpollServer');
*/

//register a function that works on server
$server ->register('getfeedDetails', array('value' => 'xsd:string'), 
                   array('return' => 'xsd:string'), 'urn:server', 'urn:server# getfeedDetails');

// create the function to fetch Data’s from Database
function getfeedDetails ()
{
   $conn = mysql_connect('localhost','root','');
   mysql_select_db('news', $conn);
   $sql = "SELECT * FROM user_story";
   $q = mysql_query($sql);
   $items = array();
   while($row = mysql_fetch_array($q)){

       $items [] = array(
            'story_url'=> $row['story_url'],
            'story_title'=> $row['story_title'],
            'story_description'=> $row['story_description'],
            'story_image'=> $row['story_image']
       );
    }
   return $items;
}

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server ->service($HTTP_RAW_POST_DATA);


      

Above code snippet will help your to access database and fetch details.

Step 4 :

Now let us open client.php and paste below code snippet into it. You have to create a client object and call your server method to retrieve the results from server.

require_once('lib/nusoap.php');
$url = "http://localhost/testserver/server.php?wsdl";
$client = new nusoap_client($url);
//Call server function
$response = $client ->call(' getfeedDetails ');

if($client->fault)
{
    echo "FAULT: Code: (".$client ->faultcode.")";
    echo "String: ".$client->faultstring;exit;
}
else
{
                $result = $response;
                $count = count($result);
?>
    >
                <table>
    <tbody><tr>
                <th>Story Url</th>
                <th>Story Title</th>
                <th>Story Description</th>
                <th>Story Image</th>
    </tr>
    
    <tr echo="" php="" rowtype=""><td></td>
                <td></td>
                <td></td>
                <td><img src="<?php echo $result[$i]['story_image']?>" type="photo" /> </td>
    </tr>
    
    </tbody></table>
 <php } ?>   
   
<style type="text/css">
    th {
        background:#007F99;
        color:#fff;
    }
</style>

      

Step 5 :

Thats it! We are done. Now go to browser and run client.php. It will call the SOAP server and fetch you the details from database.

Isn't it easy? Leave your comments below and don't forget to share this article with your friends. Thanks for reading.

Create your own helper file to generate PDF in PHP(Codeigniter)

           

 As of late, we have talked about "How to produce PDF utilizing PHP".  Today I am going to compose custom helper file to generate PDF. Did you ever thought of creating your own custom helper file to generate PDF in PHP(Codeigniter)?

Below custom helper script will generate a PDF file. You can export grid data into a PDF document.
I am going to create a single helper file to export any grid data into PDF. All you have to do is,  call my helper file and pass your data into the function, That’s all done. This script will generate PDF page.

Creating helper will help you to reuse the code and you don’t have to write much lines of codes. So let’s follow few steps as below.

 

Step 1:

Download files from dom-pdf and m-pdf and extracts it into your helper folder, ie: /system/helpers/dompdf (or mpdf ).

Step 2:

Now create your own helper and name it pdfexport_helper.php and paste the below lines of code. If you are using mpdf then use below code.




/*
* Subject          : Export pdf using mpdf
* Author           : Sanjoy Dey
* @Created Date    : 10-02-2012
* Version          : CodeIgniter_2.0.3
*
*/

if ( ! function_exists('exportMeAsMPDF')) {

    function exportAsMPdf($htmView, $fileName) 
    {

        $CI =& get_instance();
        $CI->load->library('mpdf51/mpdf');
        // $CI->mpdf=new mPDF('c','A4','','',32,25,27,25,16,13);
        $CI->mpdf->AliasNbPages('[pagetotal]');
        $CI->mpdf->SetHTMLHeader('{PAGENO}/{nb}', '1',true);
        $CI->mpdf->SetDisplayMode('fullpage');
        $CI->mpdf->pagenumPrefix = 'Page number ';
        $CI->mpdf->pagenumSuffix = ' - ';
        $CII->mpdf->nbpgPrefix = ' out of ';
        $CI->mpdf->nbpgSuffix = ' pages';
        $CI->mpdf = new mPDF('', 'A4', 0, '', 12, 12, 10, 10, 5, 5);
        $style = base_url().'/source/template/css/stylesheet.css';
        $stylesheet = file_get_contents( $style);
        $CI->mpdf->WriteHTML($stylesheet,1);                       
        $CI->mpdf->WriteHTML($htmView,2);                       
        $CI->mpdf->Output('mpdf.pdf','I');
     }
  }

If you are using dompdf then use below code.

 
  
/*
* Subject          : Export pdf using dompdf
* Author           : Sanjay
* Version          : CodeIgniter_2.0.3
*/

if ( ! function_exists('exportMeAsDOMPDF')) {

     function exportAsDomPdf($htmView, $fileName) 
     {

         $CI =& get_instance();
         $CI->load->helper(array('dompdf', 'file'));
         $CI->load->helper('file');
         $pdfName = $fileName;
         $pdfData = pdf_create($htmView, $pdfName);
         write_file('Progress Repost', $pdfData);   
     }
}

?>
 
 
Step 3:

Open your controller page and inside your function write below code.



 #Export Function goes here#
 /*This Function is used for Exporting Pdf
  * Author : Sanjay
  */

  $this->load->helper(‘pdfexport_helper.php’);
  $urlId  = $this->uri->segment('3');

    if($urlId == "export") {

       $data['pageTitle'] = "Annual Report";
       $data['htmView'] = $this->load->view('annualreport_view',$data,TRUE);
       $templateView  = $this->load->view('../template_export',$data,TRUE);
       exportAsMPdf($templateView,$data['filename']);     
          OR          
       exportAsDomPdf($htmView,$fileName)                                                                 
    }

/* Export Pdf END here */

Step 4:

That’s all you have done all steps. Click in export button to export to PDF and enjoy.

Hope this post will help you a lot to reuse your code and creating your own helper file to generate PDF in PHP(Codeigniter).

Post your queries if you have and share. Keep visiting for new posts here. All the best. Have a good day.

You also can join my group for latest technology updates in below link,

What is the Difference between ASP and ASP.NET ?



My past post was about "How to use memcache with PHP". As of late I got a request to write about "Key Differences Between Classic ASP And ASP.NET". In this post we will discuss on Difference between ASP vs ASP.NET. It is going to be very useful for your technical interview and for beginners in .NET. Here are the list of key differences between ASP and ASP.NET as below.

ASP:

i. ASP has limited OOP support. It is not supporting XML by default.

ii. Development and debugging tools unavailability. There are limited debugging tools available for ASP. Meaning that it is difficult to debug the code.

iii. In ASP we can use Visual Basic and Java for programming language.

iv. Error handling is very poor.

v. Classic ASP don't have high level programming structure. ASP pages are mix of HTML and Server side script.

vi. ASP page should have below code on the top page -


<%LANGUAGE="VBSCRIPT" CODEPAGE="960"%>

vii. It don't have built in validation control. Page validation is difficult for developers.

viii.In classic ASP it is required to restart the server in order to check latest updation on the page.

ASP.NET

i. ASP.NET is a full featured object oriented programming language.

ii. It has a full support of XML. It helps easy data exchange.

iii.There are many tools and compiler available. Microsoft Visual Studio makes your debugging job very easier.

iv. We can either use C# or VB.NET as a server side programming language.

v. ASP.NET provides three tire application architecture helps to keep your business logic and views separate. It helps on enhancing existing application without any difficulties.

vi. Error handling is very good.

vii.You should make a language directive on the page as below:


<%@Page Language="VB" CodePage="960"%> 
<%@QutputCache Duration="60" VaryByParam="none" %> 

viii. It is supporting state management.

ix. It has built in validation controls such as custom validator, range validator, regular expression, compare and require field validation control etc. It makes your job easier.

These are the key differences between classic ASP and ASP.NET. Hope this post will be helpful to you. Please don't forget to leave your comment below and share with friends. :)

How to Install Memcached in Windows 7 / WAMP ?



                 On our last article we have discussed about server side javascript Node.js. Today I am going to explain you how to install Memcache in Windows systemPresently a days, loads of notable sites like Facebook, Twitter, Digg, Youtube are utilizing open source, high performance distributed memory object caching. Which is known as Memcached. Mostly people are comfortable with windows and they are intrigued to create application in windows environment only. So here is an article to tell you the best way to install Memcached into Windows 7 (WAMP). 

             I am using WAMP server 2.1 and PHP version 5.3 in my system. I am going to tell you in step by step process.

   Step 1 :  
                 First of all you need to download memcached-1.2.6-win32-bin.zip. I search a lot and at last got the appropriate package, which you can download from here.
   Step 2 :
                  Then you need to unzip the package and you will get memcached.exe. Now what you need to do is, paste it in your directory. I have paste it in my E:\memcache\memcached.exe. and my wamp server also in E drive.
   Step 3 :
                 Now open the folder and right click on the memcached.exe and run as administrator. As we are utilizing Windows you can easily find out that option when you right click on the memcached.exe.

   Step 4:
                 Now it’s time to install the memcached in server. To do that, Just open your command prompt as administrator settings and type the path of your executable file and space and –d install then hit enter.
For your reference ,

  D:\> your path memcached.exe –d start

For further reference look at the screenshot which I added below,



You may face a error as below screenshot “The program can't install because MSVCR71.dll is missing from your computer .“ 

                            


   Step 5 :
                    In order to solve this issue you have to download the MSVCR71.dll file. I have searched a lot for the right version and finally found it. You can download it from here. Once downloaded the dll file and paste it inside system32 folder (c:\Windows\system32).  Now go to the command prompt where installation is in progress and hit enter. If you are not getting any error meaning that memcached has been installed successfully.


Step 6 :
            Once you have installed memcached in your system, go to control panel. Find out the memcached service and start the service. Otherwise you can open command prompt and type start memcached server. You will get a success message.

Step 7 :
         At long last you need to change setup in php.ini file to make memcached to work with PHP. Then only php will able to recognise memcached server. To do this you need php_memcached.dll. You can download it from here.
           
              That’s all! We are done. Now restart your WAMP server. Your memcached is ready to use and it will boost up the application performance. 

Hope this tutorial is useful. Please do not forget to leave your valuable comments below and share it with your friends. Also let me know if you are facing any issue to follow these instructions. Subscribe to our blog. 

I have also drafted "How to use memcached with PHP?" for my next article. 


   

Which Framework to use Zend or Codeigniter ??


Introduction:


Hello! Performance is always matters a lot for modern applications where millions of users visit your website daily. I personally like to use MVC framework for web application development. It helps me to build faster, structured and modular application. I also believe unless building enterprise level development you don't require large scale fatty framework like Zend, Symfony etc. You may find many questions on the web like "Which is the best PHP Framework ? " etc. My personal opinion is nothing called "best", until you know to code well. Even using good framework you may code worst. In this article I will discuss why many people prefer CodeIgniter over Zend Framework.

I trust programming should be always clean, enjoyable, fun using latest tools, updated features etc. We use Framework to handle all basic task on ease. There are various reason why Codeigniter popular, also has disadvantage over other frameworks too. I will discuss below.

CodeIgniter Vs Zend

The main reason why I love CodeIgniter because of is its performance. CodeIgniter three times faster then the Zend framework. Also CodeIgniter is faster than other popular PHP MVC frameworks. Take a look at these Benchmark test done by Rasmus Lerdorf(creator of PHP programming), here , here. And also take a look at another benchmark test. So it’s clear that CI is faster than other Framework because of tiny library. Rasmus likewise told that he loved CodeIgniter on the grounds that it is quicker, lighter and the least like a structure. 

Another primary purpose for suggestion, it has low expectation to learn and adapt. Downloads come with a tremendous user guide, which is a great documentation like PHP Manual to get started with. I have been using CodeIgniter for last 2 years for web projects as a beginner level, from my personal experience, CodeIgniter has very easy, understandable structure compared to CakePHP or Zend Framework. If you’re a beginner and want to kick start your development structured way with PHP frameworks than I recommend you to go with CodeIgniter for understanding how MVC works. And jump to some other framework when you are comfortable with.

CodeIgniter coding conventions are flexible and simple. Ironically, CakePHP, Zend has very strict coding conventions. So you should be very careful about such cases while coding.

Still question in mind "Why not Zend Framework and why CodeIgniter?" Yes! Zend is PHP company and strong supporter. Ok, So question goes here is "What is so good about Zend Framework ?" Eventually! answer is Zend contains huge set of libraries and classes compared to any other framework. But slow performer. Ok! here another great news is that You can use Zend Framework’s classes in the CodeIgniter using Hooks available in CI. So you can even use any libraries from ZEND as a component in CI. Is it not great! yes.

Conclusion:

Although there are many features may catch your eye to use CodeIgniter but as web development is grown up faster, modern development requires strong object oriented programming for implementing better, robust, modular application. Of course a OOP MVC Framework for the better development, New Framework For Fun, Enjoyable development. In such cases CodeIgniter still lacking. CodeIgniter is still backdated compare to other MVC frameworks in PHP world. Still legacy code into the core where PHP introduced next generation version as PHP7.

Read: 5 Best things you should know about PHP7

Personally, I have learned many things from CodeIgniter as a beginner and towards building easy to use, hugely powerful, Stunningly Fast and enormously efficient modular HMVC Framework as "Cygnite PHP Framework- The New Cool Kid". Version 2.0 is under active development. You may have a look into it for better experience. Some benchmark of v1.3 here, and here

You can use the below comment form to let us know your thoughts and opinion. If you like this article please do not forget to share with your friends. To receive regular updates from us, you can either follow us on Facebook, Twitter, Google+ or you can subscribe to our monthly email newsletter.

Have a good day!

How to populate a select box using jQuery ajax json, php?





Hello Friends! With the help of Ajax and PHP you can easily populate a select box without refreshing the page. You can also do it using only PHP script but requires you to refresh the page every time you change the select box value. Here is a very simple and useful example how you can populate a select box without refreshing page.

Prerequisites

1. Latest version of JQuery.

2. Very basis understanding of JSON.

3. A server side scripting knowledge to respond to Ajax request. In this tutorial I am going to use PHP as a scripting language.

Code:

There are 4 parts in this DEMO.

HTML page

The JQuery & Ajax (Client side code)

JSON structure

Server side code to populate dynamic page.

HTML:


  <select id="category">

      <option value=""> Select Job Type</option>

      <option value="1">Technical </option>

      <option value="2"> QA </option>

  </select>

 <select id="sub-category">

      <option value=""> Select Area Lead</option>

  </select>


JQUERY & AJAX REQUEST:

Include latest version of Jquery in your HTML page. Below ajax script will call server side script to get JSON data and populate select box. Add below script in your page.

 


$(function(){ 
    $('#category').change(function() {
        
        $.ajax({
            type: "POST",
            url: 'https://appsntechinfo.com/demo/list_ajax',
            data: {'categoryID': $(this).val(),'isAjax':true},
            dataType:'json',
            success: function(data) {

               var select = $("#sub-category"), options = '';
               select.empty();

               for(var i=0;i<data.length; i++) {
                 options += "<option value='"+data[i].id+"'>"+ data[i].name +"</option>";              
               }

               select.append(options);
            }
        });
    });
});


And now in your server side page you may write below to fetch data from database.

SERVER SIDE SCRIPT:

We will first validate the category id and fetch data from database then return JSON response to UI.

 

if (isset($_POST['categoryID'])) {

    $id = trim($_POST['categoryID']);
    $result = array();
    $id = mysql_real_escape_string($id);
    $res = mysql_query("SELECT * FROM sub_categories WHERE category_id = $id");
    while ($row = mysql_fetch_array($res)) {

    $result[] = array(
      'id' => $row['subcatid'],
      'name' => $row['description']
    );

    }

    echo json_encode($result);
}

SAMPLE JSON:

 

[
  {"id":10, "name": "Anderson"},
  {"id":11, "name": "Shane"},
  {"id":12, "name": "Shelly"}
]

Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 appsntech.com. All rights reserved.