akinuri akinuri - 5 months ago 11
PHP Question

Can't print stdClass property

In the following example, I'm trying to print

file_already_exists
inside another string, a query, but I get this error:

Catchable fatal error: Object of class stdClass could not be converted to string in ...




$db_items = (object) [
"cover" => (object) [
"file_already_exists" => 0, // can't print
],
"file_already_exists" => 0, // can print
];

$str = "INSERT INTO albums (file_on_system) VALUES ('$db_items->cover->file_already_exists')";

echo $str;




Using
$db_items->file_already_exists
works fine, but not
$db_items->cover->file_already_exists
. Why is that? Is there a way to print the one in
cover
?




In a simpler way

echo "$db_items->file_already_exists"; // works
echo "$db_items->cover->file_already_exists"; // doesn't work

Answer
$str = "INSERT INTO [...] VALUES ('$db_items->cover->file_already_exists')";

The parser does not know where the variable name ends, so it tries to insert $db_items into the string - and that causes the conversion issue.

Either use string concatenation

$str = "INSERT INTO albums [...] VALUES ('".$db_items->cover->file_already_exists."')";

or the complex (curly) syntax,

$str = "INSERT INTO albums [...] VALUES ('{$db_items->cover->file_already_exists}')";

Depending on where that value originates, do not neglect SQL injection!