【发布时间】:2016-11-20 08:33:44
【问题描述】:
我们正在尝试将简单的 JSON 发送到在 XAMP 上运行的本地 php 并将数据保存到 MySql,我们尝试了许多不同的代码,我们认为 Unity C# 代码是正确的但我们不确定,我们测试了许多不同的 PHP 代码,但有一半代码显示没有一半显示一些错误,我发布了最后使用的代码,欢迎任何建议。
C# 统一:
using UnityEngine;
using System.Collections;
using System.Text;
public class JSON : MonoBehaviour
{
IEnumerator Start()
{
Debug.Log ("Posting JSON...");
string URL = "http://localhost/php/page.php";
WWWForm form = new WWWForm ();
form.AddField ("username", "testuser");
form.AddField ("password", "testpass");
var headers = form.headers;
headers["content-type"] = "application/json";
WWW www = new WWW(URL, form.data, headers);
yield return www;
Debug.Log (www.uploadProgress);
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.text);
} else {
Debug.Log("WWW Error: "+ www.error);
}
}
}
PHP XAMP:
<?php
$connect = mysqli_connect("localhost","root","", "localdb");
$filename = file_get_contents('php://input');
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach ($array as $row)
{
$sql = "INSERT INTO localtable (username, password) VALUES('".$row[username]."','".$row[password]."')";
mysqli_query($connect, $sql);
}
echo $data;
?>
统一日志:
WWW 好的!:
警告: file_get_contents(username=testuser&password=testpass): 失败 打开流:中没有这样的文件或目录 C:\xampp\htdocs\php\page.php 第 8 行
警告:为 foreach( ) 在 C:\xampp\htdocs\php\page.php 行 12
JSON 数据 添加。 UnityEngine.Debug:Log(Object) c__Iterator3:MoveNext() (在资产/脚本/JSON.cs:31) UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
PHP 错误:
警告:file_get_contents():文件名不能为空 C:\xampp\htdocs\php\page.php 在第 8 行
警告:为 foreach() 提供的参数无效 C:\xampp\htdocs\php\page.php 在第 12 行添加了 JSON 数据。
编辑 1:没有错误,没有数据。
<?php
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["username"];
echo $data["password"];
?>
编辑2:
<?php
$data = file_get_contents('php://input');// $data == "username=testuser&password=testpass"
parse_str($data, $result);
echo $result["username"]; // "testuser"
echo " ";
echo $result["password"]; // "testpass"
echo " ";
?>
Unity展示数据:testuser testpass
PHP 展示:
注意:未定义变量:C:\xampp\htdocs\php\page.php 中的用户名 在第 5 行
注意:未定义变量:C:\xampp\htdocs\php\page.php 中的密码 在第 7 行
编辑 3:最终 PHP 代码未向 Mysql 添加任何记录
<?php
$data = file_get_contents('php://input');// $data == "username=testuser&password=testpass"
parse_str($data, $result);
echo $result["username"]; // "testuser"
echo " ";
echo $result["password"]; // "testpass"
echo " ";
$connect = mysqli_connect("localhost","admin","123456", "localdb");
$array = json_decode($data, true);
$sql = "INSERT INTO localtable (username, password) VALUES('".$result["password"]."','".$result["password"]."')";
mysqli_query($connect, $sql);
echo " ";
echo $queryResult = mysqli_query($connect, $sql);//Return 1
?>
【问题讨论】:
-
你遇到了什么错误?
-
在Mysql中添加空记录。
-
mysqli_query返回的值是多少? -
我必须在哪里检查?在 PHP 页面中没有显示。
-
$queryResult = mysqli_query($connect, $sql);