2016-06-10 64 views
0

在下面的例子中,我試圖打印file_already_exists另一個字符串,查詢裏面,但我得到這個錯誤:無法打印stdClass的財產

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; 

使用$db_items->file_already_exists工作正常,但不是$db_items->cover->file_already_exists。這是爲什麼?有沒有辦法打印cover


在一個更簡單的方法

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

試試'$ db_item [0] - > file_already_exists'?不知道它是否可以與對象一起工作,因爲它用於獲取數組中的第一項...更新:var_dump($ db_item-> cover)是否返回某些內容? –

+0

不是。它不會允許我將'$ db_items'視爲一個數組。 'var_dump()'retuns' object(stdClass)#3(1){ [「file_already_exists」] => int(0) }' – akinuri

+3

你在雙引號字符串中變得太複雜了。 PHP將允許一個' - >'但不能超過一個,除非你把所有東西都放在'{''db_items-> cover-> file_already_exists}'中。檢查雙引號字符串手冊中的示例。 http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double。我總是建議在'{}'中放入比簡單變量更多的東西。 –

回答

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

解析器不知道變量名結束,因此它試圖插入$db_items到串 - 並導致轉換的問題。

要麼使用字符串連接

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

complex (curly) syntax

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

不同的地方是價值起源,也不要忽視SQL注入!

+0

哈哈。我只是想着如何處理SQL注入。我對SQL很陌生。這將需要一些研究。 – akinuri