简介
继续深入一下昨天写的《Unity3D通过PHP对MySQL执行增、删、改、查》。项目中通常是由后端提供API供前端使用,本文主要介绍后端通过查询MySQL到输出JSON格式API的过程。
开始
MySQL部分。
依旧维持上节的配置。
PHP部分。
上节代码基础上,扩展一个action "show_json"。
//查,并输出JSON
if($_REQUEST['action']=="show_json")
{
$result = mysql_query("select * from highscores");
$json ="";
$data =array(); //定义好一个数组.PHP中array相当于一个数据字典.
//定义一个类,用到存放从数据库中取出的数据
class User
{
public $id;
public $name;
public $score;
}
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$user = new User();
$user->id = $row["id"];
$user->name = $row["name"];
$user->score = $row["score"];
$data[] = $user;
}
$json = json_encode($data);//把数据转换为JSON数据.
echo "{".'"user"'.":".$json."}";
}
Unity3D部分。
就是一般的GET方法。返回的www.text是json格式的,解析即可。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class readJson : MonoBehaviour
{
string url = "http://localhost/addscore.php";
IEnumerator Start()
{
WWWForm form = new WWWForm();
form.AddField("action", "show_json");
WWW www = new WWW(url, form);
yield return www;
if (!string.IsNullOrEmpty(www.error))
{
Debug.Log(www.error);
}
Debug.Log(www.text);
}
}
输出结果