【发布时间】:2018-02-11 17:33:01
【问题描述】:
所以我有一个远程(托管)MySQL 数据库,我通过 PHP 服务连接到该数据库。我需要我的 ASP.Net c# web 应用程序和我的 android 来与之通信。但是,我正在努力使用从服务中检索到的所有信息填充我的 Web 应用程序模板。例如,我想填充用户的个人资料页面。
下面是我与数据库的 PHP 连接和通信:
`// 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();
`
然后(不分享我的所有设置)这将是 asp.net c# 与我的 PHP 文件/服务通信的代码示例。
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();
}
}
另外,我不确定从该函数返回什么。 请帮忙。
【问题讨论】:
-
这个概念是以你可以使用的格式返回你需要的数据。如果您要创建两个对话者,则此格式可以随心所欲。但是,存在一些大部分标准化的方法。查找“JSON”。
-
无论您使用哪种语言或拥有多少应用程序都无关紧要。使用一个创建一个 RESTful api,并将其用作多个应用程序中的每个应用程序中的数据访问层。然后所有这些应用程序都可以使用此 api 相互集成并传递数据。
标签: c# php android mysql asp.net