1

So I have a remote(hosted) MySQL database which I connect to with a PHP service. I need both my ASP.Net c# web application and my android to communicate with it. However, I'm struggling with populating my web application template with all the information I retrieve from the service. For instance, I would like to populate a profile page of the user.

Below would be my PHP connection and communication to the database:

    `// Create connection
         $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM Vendor Where VendorId = 2"; //this is just a test
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo . $row["id"]. . $row["BusinessName"]. . $row["Location"]. . $row["Email"]. .$row["Website"]. .$row["ProductType"]. .$row["Contact"]. .$row["PaymentOption"]. .$row["ProfileImg"]."<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
` 

and then (without sharing all my setups) this would be the code sample for asp.net c# to communicate with my PHP file/service.

public void getUserInfo(int id)
        {


            string BusinessName = lblBusiness.Text.Trim();
            string email = lblEmail.Text.Trim();
            string Contact = lblPhone.Text.Trim();

            string location = lblLocation.Text.Trim();
            string Website = lblWebsite.Text.Trim();

            string payment = lblPayment.Text.Trim();

            //Variables to get information from the service
            Stream dataStream = null;
            WebResponse response = null;
            StreamReader reader = null;
            //Stores the result from the server
            string responseFromServer = null;
            try
            {
                string requestMethod = "GET";
                //Sending this data across the stream
                string postData = "&Email=" + email +   "&BusinessName=" + BusinessName + "&Website=" + Website + "&PaymentOption=" + payment + "&Location=" + location + "&ProductType=" + ProductType + "&Contact=" + Contact + "";
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                string URL = "";// url of php service location
                string contenttype = "application/x-www-form-urlencoded";
                //Create link to web service
                WebRequest request = WebRequest.Create(URL);
                //Pass the request method
                request.Method = requestMethod;
                request.ContentType = contenttype;
                request.ContentLength = byteArray.Length;
                dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                //Get response from the server
                response = request.GetResponse();
                dataStream = response.GetResponseStream();
                reader = new StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                if (dataStream != null && reader != null && response != null)
                {
                    dataStream.Close();
                    reader.Close();
                    response.Close();
                }
                //Getting the response from the service
                //string result = responseFromServer.ToString();

            }

        }

also, Im not sure what to return from that function. Please help.

2
  • The concept is to return the data you need in a format you can use. This format, if you are creating both interlocutors, can be as arbitrary as you like. However, some methods exist that are for the most part standardized. Look up "JSON". Commented Sep 3, 2017 at 6:10
  • It does not matter what language you are working with or how many application you have. Create a RESTful api with one and use it as a data access layer within each of your multiple application. then all of those application can integrate to each other using this api and pass over data. Commented Sep 3, 2017 at 6:14

2 Answers 2

2

Your php file is the "API" i pressume.
You basically need to return this from your php file.

$vendorArray = [
    "Id" => $row["id"],
    "BusinessName" => $row["BusinessName"],
    // ... this is just pseudo code, convert the array or take the array or something like that
];

header('Content-type: application/json');
echo json_encode($vendorArray);

then in asp.net you do:

var deserializedVendor = JsonConvert.DeserializeObject<Vendor>(responseFromServer);

Your vendor class has to match your jsonObject to be Deserializable

public class Vendor {

    public string Id {get;set;}

    public string BusinessName {get;set;}

    ...
}

it depends on your jsonResponse...

you can also deserialize directly into a complex item with a list of vendors like this:

var allTheVendorsDeserialized = JsonConvert.DeserializeObject<AllTheVendors>(responseFromServer);


public class AllTheVendors {

    public bool Success {get;set}

    public List<Vendor> {get;set}

}

where php:

$arr = ["Success" => true, $myArrayOfVendors];

header('Content-type: application/json');
echo json_encode($arr);
Sign up to request clarification or add additional context in comments.

Comments

1

I believe, your PHP web application is hosted and you can use the PHP service in ASP.NET with the following steps:

WebClient client = new WebClient(); //Create WebClient object

string url = "http://test.com/test.php"; //Get the URL of the PHP service

byte[] html = client.DownloadData(url); //Byte array to hold returned data from the service 

Finally use the UTF8Encoding object to convert the byte array into sring:

UTF8Encoding utf = new UTF8Encoding(); //Create an object of the UTF8Encoding class

string str = utf.GetString(html); //Convert data into string 

2 Comments

Here is another option using Curl request - stackoverflow.com/questions/16619065/curl-request-with-asp-net
Thank you! This worked. Perfectly with most if not all my functionality!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.