2013-10-12 26 views
1

我有JSON作爲輸入不能發送字符串到INSERT查詢

$page = file_get_contents('http://example.com/products.html'); 
$items = json_decode($page, true); 

,如果我把回聲$頁面;我得到水木清華這樣

{ 
"productlist":[ 
{ 
"id":"1", 
"cat":"milk", 
"prod_name":"happy milk", 
"img_url":"http://example.com/milk.jpg"}, 
{ 
"id":"2", 
"cat":"bread", 
"prod_name":"black bread", 
"img_url":"http://example.com/bread.jpg"}, 

然後,我希望把它變成MySQL數據庫

foreach($items['productlist'] as $item) { 
$id = $item['id']; 
$cat = $item['cat']; 
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, $cat)") or die(mysql_error()); 
} 

在這個階段,我什麼也得不到。如果我修改代碼到

foreach($items['productlist'] as $item) { 
$id = $item['id']; 
mysqli_query($link, "INSERT INTO table (id) VALUES ($id)") or die(mysql_error()); 
} 

我得到DB填充表 - 我有兩行prod ID。好的,我想插入表格$ cat =食品

foreach($items['productlist'] as $item) { 
$id = $item['id']; 
$cat = 'food'; 
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, $cat)") or die(mysql_error()); 
} 

但這不起作用,我得到空結果。但如果我修改查詢到

foreach($items['productlist'] as $item) { 
$id = $item['id']; 
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, 'food')") or die(mysql_error()); 
} 

我得到的結果,我尋求 - 壽在錶行,​​充滿了ID和貓

id cat 
1 food 
2 food 

沒有人知道如何通過發送字符串值到插入查詢變量?

+0

由於您已經使用了MySQLi,因此您可以使用預準備語句來應對可能的SQL注入攻擊。這也可以爲您節省單引號問題。 –

回答

0

這不起作用,因爲catString字段,需要在引號'...'之間。試試這個:

mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, '$cat')") or die(mysql_error()); 

或本:

mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, ".$cat.")") or die(mysql_error()); 
0

首先,我建議你去學習如何使用準備好的語句,因爲你得到你的代碼之外的字符串(它可能包含一些MySQL的注射)。

要回答你的問題,你需要把你周圍希望把您的查詢,因爲它是一個字符串變量一些報價,因此MySQL可以正確

mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, '$cat')") or die(mysql_error()); 
0

解釋它試試這個

mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, ".mysql_real_escape_string($cat).")") or die(mysql_error());

相關問題