I'm trying to get data from a mysql database using an object which is, in fact, a variable:
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;
outputs: OISnyJzyjA63XkPB6xla8hjms3M=
This is not working, it gives nothing:
echo 'Country: '.$user_data[$clientuid]['nation'];
This works perfectly:
echo 'Country: '.$user_data['OISnyJzyjA63XkPB6xla8hjms3M=']['nation'];
var_dump($clientuid);
yields this:
object(TeamSpeak3_Helper_String)#27 (2) {
["string":protected]=> string(28) "OISnyJzyjA63XkPB6xla8hjms3M="
["position":protected]=> int(0)
}
$user_data
is an object and has a protected
string property and obviously a magic __tostring()
method that returns the string property when the object is accessed as a string (like echo
). Without the __tostring()
method you would get:
Recoverable fatal error: Object of class TeamSpeak3_Helper_String could not be converted to string
If the string property was public
then you could just access it:
echo 'Country: '.$user_data[$clientuid->string]['nation'];
But it is protected
and not accessible and you would get:
Fatal error: Uncaught Error: Cannot access protected property TeamSpeak3_Helper_String::$string
When used as an array index it is not forcing a string, so to force it to fire the __tostring()
magic method, cast to (string)
will work (though there are probably several ways to do it):
echo 'Country: '.$user_data[(string)$clientuid]['nation'];
Or use quotes:
echo 'Country: '.$user_data["$clientuid"]['nation'];
$clientuid is an object not a simply string value, fetch value fro $clientuid first into a variable and then use that variable.
i dont have worked with TeamSpeak3_Helper_String object but after some searching i found some that probably you should use __toString()
method to convert it into string first.
refer to following links, these maybe helpful
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.