Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > Windows Store Apps > Windows Store and PHP / MySQL (C#) > Windows Store App and Retrieve Data from PHP & MySQL (C#)



Clound SSD Virtual Server

Windows Store App and Retrieve Data from PHP & MySQL (C#)

Windows Store App and Retrieve Data from PHP & MySQL (C#) บทความนี้จะเป็นการประยุกต์การเขียน Windows Store Apps เชื่อมต่อกับ HTTP ในรูปแบบของ URL ทำงานบน Web Server ในฝั่งของ Web Server ที่ถูกเรียกผ่าน URL จะถูกทำงานด้วยภาษา PHP กับ MySQL Database โดยหน้าที่ของ PHP คืออ่านข้อมูลจาก MySQL Database จากนั้นแปลงให้อยู่ในรูปแบบของ JSON ซึ่งเมื่อได้ JSON แล้ว Windows Store Apps ก็จะเรียกผ่าน URL ส่งค่า Result เพื่อแสดงผลบนหน้าจอของ Windows Store Apps

ฝั่ง Web Server (PHP/MySQL)

MySQL Table บน Web Server

Windows Store App and Retrieve Data from PHP & MySQL (C#)

CREATE TABLE `customer` (
  `CustomerID` varchar(4) NOT NULL,
  `Name` varchar(50) NOT NULL,
  `Email` varchar(50) NOT NULL,
  `CountryCode` varchar(2) NOT NULL,
  `Budget` double NOT NULL,
  `Used` double NOT NULL,
  PRIMARY KEY  (`CustomerID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `customer` VALUES ('C001', 'Win Weerachai', '[email protected]', 'TH', 1000000, 600000);
INSERT INTO `customer` VALUES ('C002', 'John Smith', '[email protected]', 'UK', 2000000, 800000);
INSERT INTO `customer` VALUES ('C003', 'Jame Born', '[email protected]', 'US', 3000000, 600000);
INSERT INTO `customer` VALUES ('C004', 'Chalee Angel', '[email protected]', 'US', 4000000, 100000);









PHP ที่ทำหน้าที่อ่านข้อมูล MySQL Database และแปลงเป็น JSON

getJSON.php
<?php
	$objConnect = mysql_connect("localhost","root","root");
	$objDB = mysql_select_db("mydatabase");

	$strSQL = "SELECT * FROM customer WHERE 1 ";

	$objQuery = mysql_query($strSQL);
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	while($obResult = mysql_fetch_array($objQuery))
	{
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++)
		{
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	}
	
	mysql_close($objConnect);
	
	echo json_encode($resultArray);
?>


เมื่อทดสอบเรียก PHP เราจะได้ Result ที่เป็น JSON ดังนี้

Windows Store App and Retrieve Data from PHP & MySQL (C#)

[
{"CustomerID":"C001","Name":"Win Weerachai","Email":"[email protected]" ,"CountryCode":"TH","Budget":"1000000","Used":"600000"},
{"CustomerID":"C002","Name":"John Smith","Email":"[email protected]" ,"CountryCode":"UK","Budget":"2000000","Used":"800000"},
{"CustomerID":"C003","Name":"Jame Born","Email":"[email protected]" ,"CountryCode":"US","Budget":"3000000","Used":"600000"},
{"CustomerID":"C004","Name":"Chalee Angel","Email":"[email protected]" ,"CountryCode":"US","Budget":"4000000","Used":"100000"}
]


รูปแบบการอ่านค่า JSON


ฝั่ง Windows Store Apps (C#)

สร้าง Class สำหรับ Mapping Column
        public class myCustomer
        {
            public string CustomerID { get; set; }
            public string Name { get; set; }
            public string Email { get; set; }
            public string CountryCode { get; set; }
            public string Budget { get; set; }
            public string Used { get; set; }
        }

ดึงค่า Result จาก Web Server ซึ่งจะได้ค่าเป็น JSON Code กลับมา
            HttpClient http = new System.Net.Http.HttpClient();
            HttpResponseMessage response = await http.GetAsync("http://localhost/myweb/getJSON.php");
            response.EnsureSuccessStatusCode();

            string resultJSON = string.Empty;
            resultJSON = await response.Content.ReadAsStringAsync();

การ Decode JSON และ Mapping กับ Column
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resultJSON));
            ObservableCollection<myCustomer> list = new ObservableCollection<myCustomer>();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ObservableCollection<myCustomer>));
            list = (ObservableCollection<myCustomer>)serializer.ReadObject(ms);

            this.lblResult.Text = string.Empty;

            foreach (myCustomer customer in list)
            {
                //customer.CustomerID.ToString();
                //customer.Name.ToString();
                //customer.Email.ToString();
                //customer.CountryCode.ToString();
                //customer.Budget.ToString();
                //customer.Used.ToString();
            }

ลองมาดูตัวอย่างแบบเต็ม ๆ

Example การเขียน Windows Store Apps อ่าค่า JSON (PHP/MySQL) มาแสดงบนหน้าจอ ของ Windows Store Apps

MainPage.xaml
<Page
    x:Class="WindowsStoreApps.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:WindowsStoreApps"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">


    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <TextBlock x:Name="lblResult" HorizontalAlignment="Left" Margin="66,83,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="20" Text="lblResult"/>

    </Grid>

</Page>

MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

using System.Net.Http;

using System.Xml.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Collections.ObjectModel;
using System.Text;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace WindowsStoreApps
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    /// 

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        public class myCustomer
        {
            public string CustomerID { get; set; }
            public string Name { get; set; }
            public string Email { get; set; }
            public string CountryCode { get; set; }
            public string Budget { get; set; }
            public string Used { get; set; }
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {

            HttpClient http = new System.Net.Http.HttpClient();
            HttpResponseMessage response = await http.GetAsync("http://localhost/myweb/getJSON.php");
            response.EnsureSuccessStatusCode();

            string resultJSON = string.Empty;
            resultJSON = await response.Content.ReadAsStringAsync();

            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resultJSON));
            ObservableCollection<myCustomer> list = new ObservableCollection<myCustomer>();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ObservableCollection<myCustomer>));
            list = (ObservableCollection<myCustomer>)serializer.ReadObject(ms);

            this.lblResult.Text = string.Empty;

            foreach (myCustomer customer in list)
            {
                //customer.CustomerID.ToString();
                //customer.Name.ToString();
                //customer.Email.ToString();
                //customer.CountryCode.ToString();
                //customer.Budget.ToString();
                //customer.Used.ToString();
                this.lblResult.Text = this.lblResult.Text + "CustomerID : " + customer.CustomerID.ToString();
                this.lblResult.Text = this.lblResult.Text + Environment.NewLine;
                this.lblResult.Text = this.lblResult.Text + "Name : " + customer.Name.ToString();
                this.lblResult.Text = this.lblResult.Text + Environment.NewLine;
                this.lblResult.Text = this.lblResult.Text + "Email : " + customer.Email.ToString();
                this.lblResult.Text = this.lblResult.Text + Environment.NewLine;
                this.lblResult.Text = this.lblResult.Text + "CountryCode : " + customer.CountryCode.ToString();
                this.lblResult.Text = this.lblResult.Text + Environment.NewLine;
                this.lblResult.Text = this.lblResult.Text + "Budget : " + customer.Budget.ToString();
                this.lblResult.Text = this.lblResult.Text + Environment.NewLine;
                this.lblResult.Text = this.lblResult.Text + "Used : " + customer.Used.ToString();
                this.lblResult.Text = this.lblResult.Text + Environment.NewLine;
                this.lblResult.Text = this.lblResult.Text + "======================";
                this.lblResult.Text = this.lblResult.Text + Environment.NewLine;
            }         
           
        }
       
    }
}


Windows Store App and Retrieve Data from PHP & MySQL (C#)

ค่าที่ได้ซึ่งถูก Decode ค่า JSON และ Loop แสดงผลบน TextBlock แบบง่าย ๆ







.

   
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2014-05-27 10:28:56 / 2017-03-19 15:03:34
  Download : No files
 Sponsored Links / Related

 
Windows Store App and Posting Data PHP & MySQL (C#)
Rating :

 
Windows Store App and Binding ListView/ListBox from JSON (C#)
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 05
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่