我正试图使用PHP将来自具有CS:GO统计数据的steam用户的数据插入MySQL数据库。我需要将stats
数组中的name
和value
值插入到MYSQL中,我将在Android应用程序中显示这些值,但我不确定具体如何执行。
代码:
<?php
$con = new mysqli('mysql6.000webhost.com','a2689951_Cheesy','ansmh1997', 'a2689951_mSicx');
if (mysqli_connect_error()) {
echo mysqli_connect_error();
exit;
}
$stats = file_get_contents("http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=<key>&steamid=76561198050187807");
$json = json_decode($stats, true);
$stats = array();
foreach ($content['playerstats']['stats'] as $stat) {
$stats[$stat["name"]] = $stat["value"];
}
$insert = "INSERT INTO user (total_kills, total_deaths) VALUES (?, ?)";
$stmt = $con->prepare($insert);
$stmt->bind_param("ss", $total_kills, $total_deaths);
?>
API示例输出:
{
"playerstats": {
"steamID": "76561198050187807",
"gameName": "ValveTestApp260",
"stats": [
{
"name": "total_kills",
"value": 35179
},
{
"name": "total_deaths",
"value": 30241
},
{
"name": "total_time_played",
"value": 2444377
},
// ...
]
}
}
由于您是初学者,有几件事需要养成做的习惯:
- 不要在PHP中使用
mysql
-函数。请改用mysqli
(它甚至支持对象定向符号!) - 设置
INSERT
语句的方式会使您的SQL注入攻击成为可能。请使用"准备好的语句" - 要从PHP脚本"返回"数据(即直接将其发送到浏览器),需要使用
echo
而不是return
- 代码中有这样一行:
json_encode($response)
,其中$response
是一个空数组。这条线不会有任何作用。json_encode()
-函数返回一个String,它包含您给它的任何内容的JSON表示。它不会更改它 - 我从你的示例中的URL中删除了API-Key,因为公开共享密钥不是一个好主意,可能会导致Valve禁止你的密钥(例如,如果恶意用户使用它向API发送请求)
现在针对您的实际问题:
foreach ($json->playerstats->stats as $stat) {
$stats[$stat["name"]] = $stat["value"];
$total_kills = $stats["total_kills"];
$total_deaths = $stats["total_deaths"];
我认为,对于循环实际重复了这段代码的哪一部分,可能会有一些困惑。它不是第一行,而是整个正文(用{}
括号括起来)。
问题是,您将只从JSON获得$stats
-数组中的第一个条目,即total_kills
。但你想要所有这些,所以你的循环应该只运行这一部分:
foreach ($content['playerstats']['stats'] as $stat) {
$stats[$stat["name"]] = $stat["value"];
}
// Continue as you did...
然后,这将使请求中的整个数据成为您期望的格式,因此对$stats
的第二次访问将正常工作。
我认为您的插入语句需要在foreach中,请尝试此操作。
$con = mysqli_connect("mysql6.000webhost.com", "a2689951_steam", "password", "a2689951_playerdata");
$stats = file_get_contents("http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=(MyKey)&steamid=(PlayerID)");
$json = json_decode($stats, true);
$stats = array();
foreach ($content['playerstats']['stats'] as $stat) {
$stats[$stat["name"]] = $stat["value"];
$total_kills = $stats["total_kills"];
$total_deaths = $stats["total_deaths"];
$insert = "INSERT INTO user (total_kills, total_deaths) VALUES ('$statement', 'siss', $total_kills, $total_deaths)";
if ($con->query($insert) === TRUE) {
$response = array();
json_encode($response);
return json_encode($response["success"]);
} else {
return "Error: <br>" . $con->error;
}
}