使用变量从mysql db获取数据

问题描述 投票:1回答:2

我正在尝试使用一个实际上是变量的对象从mysql数据库中获取数据:

try {
$mysqlcon = new PDO($dbserver, $db['user'], $db['pass'], $dboptions);
// Selecting database "user" to get data about a specific client
if(($user_data = $mysqlcon->query("SELECT * FROM $dbname.user;")->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC)) === false)
{
    echo '$#!+ happens, Critical DataBase Error!';// error on db select
}

echo 'Country: '.$user_data[$clientuid]['nation']; // This is not working, it gives nothing
echo 'Country: '.$user_data['OISnyJzyjA63XkPB6xla8hjms3M=']['nation']; // BUT This works perfectly               
// DEBUGGING
echo $clientuid; // it outputs: OISnyJzyjA63XkPB6xla8hjms3M=
var_dump($clientuid); // and this is the important thing, it outputs this: object(TeamSpeak3_Helper_String)#27 (2) { ["string":protected]=> string(28) "OISnyJzyjA63XkPB6xla8hjms3M=" ["position":protected]=> int(0) }
}
catch (PDOException $e)
{
    echo "Database Connection failed: ".$e->getMessage()."\n";
    exit;
}

echo $clientuid;输出:OISnyJzyjA63XkPB6xla8hjms3M=

这不起作用,它什么都没有:

echo 'Country: '.$user_data[$clientuid]['nation'];

这非常有效:

echo 'Country: '.$user_data['OISnyJzyjA63XkPB6xla8hjms3M=']['nation'];                

var_dump($clientuid);得出这个:

object(TeamSpeak3_Helper_String)#27 (2) {
    ["string":protected]=> string(28) "OISnyJzyjA63XkPB6xla8hjms3M=" 
    ["position":protected]=> int(0)
}
php mysql string variables protected
2个回答
1
投票

$user_data是一个对象,有一个protected字符串属性,显然是一个神奇的__tostring()方法,当对象作为字符串访问时返回字符串属性(如echo)。没有__tostring()方法,你会得到:

可恢复的致命错误:TeamSpeak3_Helper_String类的对象无法转换为字符串

如果字符串属性是public,那么你可以访问它:

echo 'Country: '.$user_data[$clientuid->string]['nation'];

但它是protected,无法访问,你会得到:

致命错误:未捕获错误:无法访问受保护的属性TeamSpeak3_Helper_String :: $ string

当用作数组索引时,它不会强制使用字符串,因此要强制它触发__tostring()魔术方法,强制转换为(string)会起作用(尽管可能有几种方法):

echo 'Country: '.$user_data[(string)$clientuid]['nation'];

或者使用引号:

echo 'Country: '.$user_data["$clientuid"]['nation'];

-1
投票

$ clientuid是一个对象而不是简单的字符串值,首先从$ clientuid获取值到变量中,然后使用该变量。

我没有使用TeamSpeak3_Helper_String对象,但经过一些搜索我发现一些可能你应该使用__toString()方法将其转换为字符串优先。

请参考以下链接,这些可能会有所帮助

https://hotexamples.com/examples/-/TeamSpeak3_Helper_String/-/php-teamspeak3_helper_string-class-examples.html

https://docs.planetteamspeak.com/ts3/php/framework/class_team_speak3___helper___string.html#a5558c5d549f41597377fa1ea8a1cefa3

© www.soinside.com 2019 - 2024. All rights reserved.