dongqi8114
2012-05-04 12:48 阅读 134

通过C#将JSON数据POST到PHP并在MYSQL中存储值

My Class in C# which should be send to PHP:

MyData data = new MyData();
data.Name = "MyName";
data.Type = "MyType";
data.ID = 1;
data.Description = "MyLongDescription...";

How do I send it to PHP via C# in JSON format? And how do I retrieve it in PHP? The next step should be to insert the submitted data/values into a MySQL DB.

C# -> Send some JSON Data to PHP -> Write JSON Data to MYSQL DB via PHP

Sample Database: MyData(varchar Name, varchar Type, int ID, varchar Description)

My current PHP Code:

$json = json_decode($input,true);

$connection = mysql_connect("localhost","root","");
if (!$connection)
{
     die(mysql_error());
}

mysql_select_db("MyDataDB", $con);

mysql_query("INSERT INTO MyData (Name, Type, OtherID, Description) 
VALUES('$json[Name]','$json[Type]','$json[ID]','$json[Description]')");

Any ideas?

Thanks for your efforts.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dongshou6788 dongshou6788 2012-05-04 12:53

    C# code to encode:

    var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    string json = jsonSerializer.Serialize(yourCustomObject);
    

    PHP code to decode:

    $decoded = json_decode($received_json_string);
    

    What have you tried, by the way?

    点赞 评论 复制链接分享
  • douwei8672 douwei8672 2012-05-04 13:02

    I'll answer this, but to Quentin's point, you've got a lot going on.

    There is no direct interop between C# and PHP so you'd need to expose a web service from PHP and consume it in your C#. Better yet, have the C# save directly to mysql and don't worry about interop.

    点赞 评论 复制链接分享

相关推荐