2014-07-25 75 views
1

我想插入一個數組中的數據行到mysql數據庫中的表。我是一個初學者,在PHP,MySQL和有關它的知識很少。我只是想了解更多。如果你可以試試這個會很棒。插入一個數組到表中使用for循環

,我想插入的代碼如下:

for($x=0; $x<2; $x++) 
{ 
    $data[$x]['title']   = $titleQuery->item($x)->nodeValue; 
    $data[$x]['titleHrefQuery'] = $titleHrefQuery->item($x)->nodeValue; 
    $data[$x]['food']   = $foodQuery->item($x)->nodeValue; 
    $data[$x]['locality']  = $localityQuery->item($x)->nodeValue; 
    $data[$x]['rating']   = $ratingQuery->item($x)->nodeValue; 
    $data[$x]['cost']   = $costQuery->item($x)->nodeValue; 
} 

我特林使用下面給出的代碼中插入:顯示沒有添加

$query = "INSERT INTO table (`title`, `link`, `food`, `locality`, `rating`, `cost`) VALUES 
     ('" . $titleQuery->item($x)->nodeValue . "', 
     '".$titleHrefQuery->item($x)->nodeValue."', 
     '".$foodQuery->item($x)->nodeValue."', 
     '".$localityQuery->item($x)->nodeValue."', 
     '".$ratingQuery->item($x)->nodeValue."', 
     '".$costQuery->item($x)->nodeValue."')"; 

$result = mysql_query($query); 

if($result) 
{ 
    echo ("Success"); 
} 
else 
{ 
    echo ("Not added"); 
} 

但每一次。請幫忙!!

+0

加上'打印mysql_error()'執行查詢 – user4035

+0

[請不要使用mysql_ *函數在新的代碼(後http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – MLeFevre

+0

也使用if($ result!== FALSE){...}而不是我f($結果){...} – GCallie

回答

3

變化

INSERT INTO table 

INSERT INTO `table` 

,因爲表是一個保留keyword.And如果您使用保留的關鍵字作爲表名或列名,則必須將它們用背蜱( ````````````````最好不要使用任何預留關鍵字。所以如果你可以更改名稱,那麼它將是最好的選擇。你可以檢查更多的這些問題

  1. How do I escape reserved words used as column names? MySQL/Create Table

  2. Can we have the table name as "option" in MySQL?

  3. H2 database column name "GROUP" is a reserved word

+0

哦,多麼傻!謝啦...!! – shivam

+0

歡迎@ user3761273 ...... –

2
"INSERT INTO table...." should be "INSERT INTO `table`..." 

Try to avoid mysql key names as table name or field name it would help you in writing better sql queries. 

Use following line to see mysql error so can you easily track the reason why you are getting error - 

if($result) 
{ 
    echo ("Success"); 
} 
else 
{ 
    echo ("Not added"); 
    echo mysql_errno($link) . ": " . mysql_error($link). "\n"; 
} 
相關問題