将值从数据库传递到 API

Passing value from DB to API

本文关键字:API 数据库      更新时间:2023-09-26

我在这里要做的是,当我添加一个新用户时,$steamids将获得该新值。但问题是我根本没有获得信息。似乎它没有从数据库中获取属性steam_id。我能在这里做什么?

<?php    
    $dbh = new PDO('mysql:host=localhost;dbname=csgo', 'root', '');
    $sql = "SELECT * FROM users";
    $users = $dbh->query($sql);
    foreach($users as $r) {        
        $steamids = $r['steam_id'];        
        $APIKEY = '*******************';
        $steamAPI = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?steamids=$steamids&key=$APIKEY&format=json";
        $json_object = file_get_contents($steamAPI);
        header('Content-Type: application/json');
        echo $json_object;
    }

当我只将普通 ID 添加到$steamids时,它工作正常。但显然,我只能显示一个用户。我想显示多个,但我不知道我的代码出了什么问题。

好的!编辑

所以我这样做了:

<?php
$dbh = new PDO('mysql:host=localhost;dbname=csgo', 'root', '');
$sth = $dbh->prepare("SELECT steam_id FROM users");
$sth->execute();
$result = $sth->fetchColumn();
$steamids = $result;
$APIKEY = '*******';
$steamAPI = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?steamids=$steamids&key=$APIKEY&format=json";
$json_object= file_get_contents($steamAPI);
header('Content-Type: application/json');
echo $json_object;

现在我得到了steam_id,但只有第一行,我应该如何获得每个人的 ID?

试一试(使用fetch循环)

$dbh = new PDO('mysql:host=localhost;dbname=csgo', 'root', '');
$sth = $dbh->prepare("SELECT steam_id FROM users");
$sth->execute();
while($result = $sth->fetch())
{
    $steamids = $result['steam_id'];
    $APIKEY = '*******';
    $steamAPI = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?steamids=$steamids&key=$APIKEY&format=json";
    $json_object= file_get_contents($steamAPI);
    echo $json_object;
}

大概是这个?

<?php 
error_reporting(-1); // Example where to add the PHP error reporting
ini_set('error_reporting', E_ALL); // if error reporting is switched off
header('Content-Type: application/json');
$dbh = new PDO('mysql:host=localhost;dbname=csgo', 'root', '');
$sth = $dbh->prepare("SELECT `steam_id` FROM `users`");
$APIKEY = '*******************';
$steamids = array();
if ($sth->execute()) {
    while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        $steamids [] = $row["steam_id"];
        $steamAPI = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?steamids=". $row["steam_id"] ."&key=". $APIKEY ."&format=json";
        $json_object = file_get_contents($steamAPI);
        echo $json_object;
        sleep(1); // To pause the script for 1 second, OR try "usleep(500000);" for 0.5 second sleep, yes, "usleep".
    }
}
echo "Test";