2014-01-14 34 views
0

我正在研究一個PHP代碼,它將從XML中讀取數據,將它存儲在MySQL中。到目前爲止,我已經指出了從XML文件中讀取數據並在網站上回應它的地方。這裏是代碼:PHP - XML到MySQL

<?php 

//mysql connection 
mysql_connect("localhost", "root", "") or die(mysql_error()); 
mysql_select_db("bet_sql") or die(mysql_error()); 

$xml = simplexml_load_file('http://cachepricefeeds.williamhill.com/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=46&marketSort=MR&filterBIR=N'); 

foreach ($xml->response->williamhill->class->type as $type) { 
    $type_attrib = $type->attributes(); 
    $type_attrib['id']; 
    $type_attrib['name']; 
    foreach ($type->market as $event) { 
    $event_attrib = $event->attributes(); 
    $event_attrib['id']; 
    $event_attrib['name']; 
    $event_attrib['date']; 
    $event_attrib['url']; 
    foreach ($event->participant as $participant) { 
     $participant_attrib = $participant->attributes(); 
      $participant_attrib['name']; 
      $participant_attrib['oddsDecimal']; 
    } 
    } 

    mysql_query("INSERT INTO games (type_id, type_name, event_id, event_name, event_url, participant_name, participant_odds) 
      VALUES ($type_attrib[id], $type_attrib[name], $event_attrib[id], $event_attrib[name], $event_attrib[url], $participant_attrib[name], $participant_attrib[oddsDecimal]) ") 
      or die(mysql_error()); 
} 
?> 

我在做什麼錯誤的mysql_query?我正在處理此消息:

您的SQL語法錯誤;檢查對應於你的MySQL服務器版本使用附近的正確語法手冊「甲級聯賽,134465843,ZULTE-Waregem的v亨克 - 75分鐘投注,」在第2行

感謝您的幫助!

+1

謹慎的只是一個字,因爲我看到你的體育書數據搞亂。如果你遇到這種類型的錯誤,你必須是MySQL的新手,如果沒有人監督這個過程,可能不應該在生產環境中處理這些數據。 – Jasper

+1

您沒有在查詢中引用數據,您應該使用PDO或MySQLi,它們允許您準備語句。 – Jon

回答

1

這是爲什麼你應該使用prepared statement來做到這一點的主要例子。它不僅比反覆運行同樣的INSERT聲明更快,還能避免轉義問題,並使您擺脫陳舊的mysql_query函數。

我猜什麼數據類型是爲bind_param

$msyqli = new mysqli('localhost'...); //Your connection credentials here 
$sql = 'INSERT INTO games (type_id, type_name, event_id, event_name, event_url, participant_name, participant_odds) 
VALUES (?, ?, ?, ?, ?, ?, ?, ?)'; 
$prep = $mysqli->prepare($sql); 
foreach ($xml->response->williamhill->class->type as $type) { 
    //Truncated the other code out for example  
    $prep->bind_param('isissss', $type_attrib[id], $type_attrib[name], $event_attrib[id], 
    $event_attrib[name], $event_attrib[url], $participant_attrib[name], $participant_attrib[oddsDecimal]); 
    $prep->execute(); 
} 
+0

你應該舉一個例子,使這個有用的答案^^ – Jon

+0

你能幫助我多一點與準備好的聲明?如何在我的情況下做到這一點?如果沒有,謝謝資源! – bundyal

+0

添加了一個示例。它是爲演示而縮寫的 – Machavity

0

與插入查詢的問題被

  • 數組鍵是沒有一個給出的報價,這將導致警告
  • 值爲沒有正確逃脫。它可能是語法錯誤的主要原因。

    mysql_query("INSERT INTO games (type_id, type_name, event_id, event_name, 
    event_url, participant_name, participant_odds) 
    VALUES ($type_attrib[id], $type_attrib[name], $event_attrib[id], 
    $event_attrib[name], $event_attrib[url], $participant_attrib[name], 
    $participant_attrib[oddsDecimal])" 
    ) or die(mysql_error()); 
    
+0

你放的代碼不起作用。 – Jon

+0

我沒有放任何代碼,它與問題中指定的相同。這只是供參考和支持2點以上。 – Hrishi