尝试通过我的本地主机作为后端和 c# 作为前端为我的 MySQL 数据库创建项目


Trying to create items to my MySQL database via my localhost as backend and c# as frontend

所以我有一个后端代码,我将数据库中的结果作为数组 Jobject 回显出来,还有一个代码(我将首先显示),当我想通过我的前端在我的数据库上创建一些东西时,我试图让一些事情发生。

所以我的问题是,我应该如何调整代码的第一部分,以便我的前端代码可以访问它,以便用户放入前端代码的信息进入数据库?

<?php 
$mysql_pekare= new mysqli ("host", " user","pass", "db");
$stmt = $mysql_pekare->prepare("INSERT INTO Events(`Name`, `Title`) VALUES(?,?)");
$stmt->bind_param("ss", $namn, $age);
$stmt->execute();
$stmt->close();
$mysql_pekare->close();
?>

最后,这是我的前端代码(C#),我尝试访问数据库和PHP代码,并从前端向数据库创建一些东西:

static public async Task <bool>  createOurMainInfo (string userId, string thename, string thetitle)
    {
        var httpClientRequest = new HttpClient ();
        var postData = new Dictionary <string, string> ();
        postData.Add ("Name", thename);
        postData.Add ("Title", thetitle);
        var jsonRequest = JsonConvert.SerializeObject(postData);
        HttpContent content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json");
        var result = await httpClientRequest.PostAsync("http://localhost/Events.php", content);
        var resultString = await result.Content.ReadAsStringAsync ();
        return  true;
     }

更新的代码:

$value1 = json_decode(file_get_contents('php://input'));
$value2 = json_decode(file_get_contents('php://input'));
$mysql_pekare= new mysqli ("", "","", "");
$stmt = $mysql_pekare->prepare("INSERT INTO Events(`Name`, `Title`) VALUES(?,?)");
$stmt->bind_param("ss", $value1, $value2);
$stmt->execute();
$stmt->close();
$mysql_pekare->close();
echo $value1->Name;
echo $value2->Title;
c# 代码将 2 个参数作为 Name 发布,将 Title 作为 json,

因此您的第一个 php 代码应以 json 格式将 2 个参数命名为 Name 和 Title,并将这 2 个参数提交到插入查询中,代替 $namn 和 $age。

由于将数据发布为 json,因此不能直接使用 $_POST。 php://input 使您能够读取原始的 post 输入,json_decode() 可用于将 JSON 字符串的内容解码为对象。

$value = json_decode(file_get_contents('php://input'));
echo $value->Title; //should return title

显然,我会在 php 代码中添加一些身份验证和授权,并在将 json 参数提交到数据库之前对它们进行一些输入检查。