How To Write A Simple PHP/MySQL Web Service for a C# Application

Posted By: Achchuthan Yogarajah - December 27, 2014
Creating a basic web service is very simple and encourages your users to spread the word about your website or service. Want more traffic? Want your website to grow without you putting in all the effort? Create a web service!

Web services are taking over the world. Why not use the same model for your own sites? Here's how to create a basic web service that provides an XML or JSON response using some PHP and MySQL.

As a C# Application developer, it can be really useful to be able to write your own simple web services that integrate with your application.
For example, you may wish to display some news updates that come from your web server, and display it on startup. Or perhaps store some user data “in the cloud”. Your imagination is the only limit!

In this first tutorial you’ll go step-by-step through the process of creating a simple web service. I included in my latest application.

How it works?


Download Project 

Step 1: Creating the Database

The first step of this project is to create the database tables you’ll need. For the purposes of this tutorial, you’ll need create database tables:

Database name: simplerestful
Create a database simplerestful and create a table testdata /upload this testdata.sql file into the databse.

testdata.sql
-- phpMyAdmin SQL Dump
-- version 4.0.4.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Feb 11, 2014 at 03:55 PM
-- Server version: 5.6.11
-- PHP Version: 5.5.1

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `simplerestful`
--

-- --------------------------------------------------------

--
-- Table structure for table `testdata`
--

CREATE TABLE IF NOT EXISTS `testdata` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `age` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;

--
-- Dumping data for table `testdata`
--

INSERT INTO `testdata` (`id`, `name`, `age`) VALUES
(10, 'Achchuthan', '24'),
(11, 'Rajh', '23');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Step 2: C# Application  code for send String to the Server

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SimpleRESTful
{
    public partial class Form1 : Form
    {
        //this is proxy setting 
        private bool proxy_setting = false;//not connected with proxy server

        //this is your proxy username,password,ip
        private string proxy_ip = "http://192.168.1.1";//your proxy server
        private string port = "80"; //proxy password
        private string username = "username"; //proxy username
        private string password = "password";  //proxy password 
 
        //this is for where you want to pass your date URL
        private string post_url = "http://localhost/SimpleRESTful/cash.php";
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string name = textBox1.Text; //get name from text box
            string age = textBox2.Text; //get name from from text box 
            label3.Text = "POST data { Name :" + name + "  Age : " + age + " }";

            //this is your post data

            string POST_DATA = "name=" + name + "&age=" + age;
            
            //sent data to remote server
           string responseString = DataRequestToServer(POST_DATA, post_url);//get responce message from remote server

            //show the responce message
           MessageBox.Show(responseString,"Message from Server");

        }
        public string DataRequestToServer(string postData, string url)
        {
            try
            {
                // Create a new request to the mentioned URL.    
                HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);
                if (proxy_setting == true)
                {
                    connectProxy(httpWReq);
                }
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(postData);
                httpWReq.Method = "POST";
                httpWReq.ContentType = "application/x-www-form-urlencoded";
                httpWReq.ContentLength = data.Length;
                using (Stream stream = httpWReq.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
                HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
                string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                return responseString;

            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

        public void connectProxy(HttpWebRequest httpWReq)
        {
            // Obtain the 'Proxy' of the  Default browser.  
            IWebProxy proxy = httpWReq.Proxy;
            WebProxy myProxy = new WebProxy();
            Uri newUri = new Uri(proxy_ip);
            // Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
            myProxy.Address = newUri;
            // Create a NetworkCredential object and associate it with the  
            // Proxy property of request object.
            myProxy.Credentials = new NetworkCredential(username, password);
            httpWReq.Proxy = myProxy;
        }

        
    }
}

Step 3:  PHP Receiver Code

GET vs POST
Now that we know things are working, it’s almost time to implement the full behavior. But first, let’s talk about our strategy for the web service.
We know we need to pass some data from the c# application to our web service. Specifically, we need to tell the web service the name of the application.
But how can we pass this data? If you aren’t familiar already, there are two ways to pass data to a web service – via GET (the normal way), or via POST (typically used for posting data to a web form).

Depending on which one you choose, the parameters get passed differently:
If you choose GET, the parameters are part of the URL.
If you choose POST, the parameters are passed as part of the request body.

config.php

Database connection configuration code 
$con=mysqli_connect("localhost","root","","simplerestful");
 if (mysqli_connect_errno()){
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }


cash.php

With the number of persons hitting your web service (hopefully), you'll need to do adequate validation before attempting to connect to the database to avoid injection attacks. Once we get the desired results from the database, we cycle through the results to populate our return results array. Depending upon the response type desired, we output the proper header and content in the desired format.

Using post method to get post data from C# Application

require_once("config.php"); 

if (isset($_POST['name'])) {
    $name = $_POST['name'];
 $age = $_POST['age'];
    mysqli_query($con, "INSERT INTO `testdata` (`name`, `age`) VALUES ('$name', '$age')"); 
    echo "Welcome ! $name";
}

You should be able to understand the general idea of how things work here by looking at the comments inline with the code Also, here’s a few things I’d like to point out:

  • isset is a handy function in PHP you can use to tell if a particular variable has been set. We use it here to make sure all the required POST parameters are passed in.

OpenShift: Develop, Host, and Scale Your Apps in the Cloud - Introduction

Posted By: Achchuthan Yogarajah - December 23, 2014
OpenShift Online | Source: www.openshift.com

What is OpenShift?

OpenShift is Red Hat's Cloud Computing Platform as a Service (PaaS) offering. OpenShift is an application platform in the cloud where application developers and teams can build, test, deploy, and run their applications.

OpenShift takes care of all the infrastructure, middleware, and management and allows the developer to focus on what they do best: designing and coding applications.

AngularJS: Hello World Example and Introduction

Posted By: Achchuthan Yogarajah - December 19, 2014

AngularJS, a JavaScript framework developed by a Googler and supported by Google has become quite a buzz word in past few months. More and more developers are using it and thus the community has grown significantly. How much you can do with few lines of code in Angular is mind-boggling. Any one with basic JavaScript, HTML background can start working in AngularJS without any hassle.

Run Moses for the first time and create baseline system in Ubuntu 14.04 LTS

Posted By: Achchuthan Yogarajah - December 15, 2014
This guide assumes that you have successfully installed Moses, and would like to see how to use parallel data to build a real phrase-based translation system. The process requires some familiarity with UNIX and, ideally, access to a Linux server. It can be run on a laptop, but could take about a day and requires at least 2G of RAM, and about 10G of free disk space (these requirements are just educated guesses, so if you have a different experience then please mail support).

If you want to save the effort of typing in all the commands on this page (and see how the pros manage their experiments), then skip straight to the experiment management system instructions below. But I'd recommend that you follow through the process manually, at least once, just to see how it all works.

How to install moses on ubuntu 14.04 (x64) LTS ?

Posted By: Achchuthan Yogarajah - June 14, 2014
Phrase-based statistical machine translation has emerged as the dominant paradigm in machine translation research. However, until now, most work in this field has been carried out on proprietary and in-house research systems. This lack of openness has created a high barrier to entry for researchers as many of the components required have had to be duplicated. This has also hindered effective comparisons of the different elements of the systems.

Read text file and convert to Matrix / array of array in Perl

Posted By: Achchuthan Yogarajah - May 17, 2014
This article about How to crate a  multidimensional array ? and how to read text file and convert to matrix .First we consider an array of array , An array of arrays is a two-dimensional structure that consists in an array whose elements are references to other arrays.Each element of the array (let's call them sub arrays) is also an array, so we use anonymous arrays to define each sub array.

Find the sum of a list of numbers in Perl

Posted By: Achchuthan Yogarajah - May 08, 2014

In this article , simply create a array (@list) and assign elements into the array(@list).First find the sum of the list and second code is to find sum of odd numbers and even numbers separately of the array(@list) of numbers.

Find frequency of each word in the paragraph in perl

Posted By: Achchuthan Yogarajah - March 11, 2014
This article about read a text  file and count the frequency of each word in the paragraph .First we read text file and split the paragraph using space and assign into a array (@row_elements) .for every elements in (@row_elements) , increase word count (%words_count) by one . 

Perl Basic Datatypes

Posted By: Achchuthan Yogarajah - March 10, 2014
This program uses variables of each of three basic types: scalar, array, and hash. Scalar variables can be numbers or strings, and the language will understand how to treat the data by the context of its use. An array is a linear collection of scalar data. A hash, or associative array, is a built-in data type that will associate a "key", with a piece of data.

What are RESTful Web Services ?

Posted By: Achchuthan Yogarajah - February 16, 2014
This is my first post on RESTful web service . Lets start with the basic concept of REST

What are RESTful Web Services ?

REST stands for Representational State Transfer . Its a key idiom that embraces a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URLs. REST was first described by Roy Fielding in the year 2000.

What is Perl ? - Beginner's Introduction

Posted By: Achchuthan Yogarajah - February 10, 2014
Perl is a programming language developed by Larry Wall, especially designed for text processing. It stands for Practical Extraction and Report Language. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. If you have basic knowledge of C or UNIX Shell then PERL is very easy to learn. This tutorial gives a complete understanding on Perl

UDP and TCP: Comparison of Transport Protocols

Posted By: Achchuthan Yogarajah - February 10, 2014
You have most likely heard of sockets, and are probably aware that there are two main types: TCP and UDP. When writing a network game, we first need to choose what type of socket to use. Do we use TCP sockets, UDP sockets or a mixture of both?

Copyright © 2010 - 2019 Believe in Yourself - Achchuthan Yogarajah . Designed by Templateism .