php - 使用 Unity 的 ID 从数据库表中获取值
问题描述
我有一个带有值的数据库表,主键是 ID。现在我正在尝试从 Unity 接收具有引用 ID 的表的值。如何将引用的 ID 从 Unity 发送到这个 php 文件,以便只接收来自这个 ID 的值。
目前我正在接收来自所有 ID 的表的所有值。
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class CheckForExistingID : MonoBehaviour {
public string[] Items;
public string ID = "001"; //Referenced ID
public string Name;
public string Age;
void Start () {
StartCoroutine (ReceiveValues());
}
IEnumerator ReceiveValues () {
WWW data = new WWW ("http://localhost/GetValue.php?id="+ID);
yield return data;
if (data.error != null) {
print (data.error);
} else {
print ("Received");
dataString = data.text;
Items = dataString.Split (';');
Name = Items[0];
Age = Items[1];
}
}
}
获取值.php
<?php
...
...
...
$id = $_GET['id'];
$sql = "SELECT Name, Age FROM Students WHERE ID = $id";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result)){
echo "".$row['Name'] . ";";
echo "".$row['Age'] . ";";
}
}
?>
解决方案
注意不要像derHugo指出的那样使用WWW ,它现在已经过时了。同样,使用准备好的语句清理所有数据。跳到编辑标记以查找更新的答案。
我不确定您是否正确发布了数据。您应该使用 a WWWForm
,添加您想要的字段,然后在 PHP 端处理它们。我还会认真考虑在 PHP 中添加某种形式的错误处理,并使用回显来了解是否有故障。
在移动设备上,请暂时原谅格式设置,如果需要,我稍后会修复它。
string url = "http://localhost/GetValue.php";
WWWForm form = new WWWForm();
form.AddField("id", "TheIDHere");
WWW www = new WWW(url, form);
yield return www;
...
在 PHP 方面,它看起来像
<?php
if (isset($_REQUEST["id"])) {
echo "Received ". $_REQUEST["id"]. " success!";
exit();
} else {
http_status_code(400);
echo "Request Failed";
}
编辑:正如 derHugo 所指出的,WWW
现在已过时,并由WebRequests
. 上面的 c# 代码应该是这样的
WWWForm form = new WWWForm();
form.AddField("id", "yourID");
UnityWebRequest www = UnityWebRequest.Post("http://localhost/GetValue.php", form);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Sucess");
}
同样,derHugo 指出您根本没有清理数据,因此您将受到 SQL 注入的影响。这大致是您想要使用准备好的语句所做的事情
// prepare a statement using the ID
$stmt = $mysqli->prepare("SELECT Name, Age FROM Students WHERE ID = ?");
// bind the ID from our POST
$stmt->bind_param("i", $_POST['id']);
// execute our prepare statement
$stmt->execute();
// store the result
$stmt->store_result();
// we have no found id
if($stmt->num_rows === 0) exit('No Data');
// bind the results we are looking for from our prepared statement
$stmt->bind_result($idName, $idAge);
// fetch the results from the table
$stmt->fetch();
// echo your results to Unity
echo $idName;
echo $idAge;
// deallocate the statement
$stmt->close();
推荐阅读
- swiftui - 为什么这个自定义形状会占据整个垂直空间?
- r - 合并 R 中的 df 并将列从 df 2 - 12 重命名为 df 1 的列名
- python - 获取列表上的操作作为熊猫中包含列表或字符串的新列
- javascript - 使用来自另一个函数的请求选项调用函数始终为空
- java - 如何在 Java 中创建相对路径?
- php - php中的选择标签中的选定选项来自
- python - 如何匹配具有范围内日期列表的记录?
- python-iris - 使用 iris 在 GRIB 中查找参数
- r - Why does the stacked bar chart not match values in table?
- java - Spring framework:ConstraintViolationException 仍然被抛出,即使我在 @Valid 带注释的变量之后添加了一个 BindingResult