Skip to content

Instantly share code, notes, and snippets.

@stilllisisi
Created March 11, 2020 10:56
Show Gist options
  • Save stilllisisi/124a5ed2729c70065169d18b40ce6b98 to your computer and use it in GitHub Desktop.
Save stilllisisi/124a5ed2729c70065169d18b40ce6b98 to your computer and use it in GitHub Desktop.
【游戏-网络】Unity和PHP的Http数据交互。经常需要做一些简单的数据统计,可以使用Socket写的服务端交互,也可以用http的交互。本篇文章实现Unity与PHP的Http数据交互。
//PHP注册代码,每次访问都需要开关一次数据库,可以借助数据库连接池来解决此问题。
<?php
include 'Common.php';//引用包含Check方法的php文件,这个是自己写的,一种检测非法手段,可以百度下,也可以不写
$name=Check($_POST["name"]);//PHP获取form内容的方法,$name=$_POST["name"];
$pass=Check($_POST["pass"]);
$con=mysql_connect("127.0.0.1","root","");//连接mysql
if(!$con)
die("Could not connect:".mysql_error());//如果连接失败则结束
mysql_select_db("CreateData",$con);//选择数据库
mysql_query("set names utf8");//设置utf8,否则中文会乱码噢
$com= mysql_query("select pass from Login where name='$name'");//查询是否有此名称
if(mysql_num_rows($com)!=0)
{
die("-1");//username already exist;//如果有则结束函数,并打印-1
}
mysql_query("insert into Login(name,pass,lasttime) values('$name','$pass',now())");//插入用户名
$com=mysql_query("select uid from Login where name='$name'");
$com=mysql_fetch_array($com);
$com=$com["uid"];
echo "$com";//打印uid
mysql_close($con);//关闭数据库
?>
//Unity访问代码
public void SendUserCor(string url, string name, string password)
{
StartCoroutine(SendUser(url, name, password));
}
IEnumerator SendUser(string url,string name,string password)
{
//这个官方有对应案例
WWWForm from = new WWWForm();//建立表单
from.AddField("name", name);//添加数据
from.AddField("pass", password);
WWW www = new WWW(url, from);//建立WWW
yield return www;
if (www.error != null)
{
Debug.Log(www.error);
}
else
{
Debug.Log(www.text);//获得返回的数据
//-1 用户名已存在
//>0 为uid编号
}
}
@stilllisisi
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment