2015-04-07 57 views
0

這裏發生了一些奇怪的事情,通常我不會有問題,或者我可能只是累了。但是MySQL不會接受我的語法來將JSON插入到表中。MySQL不會插入JSON

foreach ($newArray as $k => $v) { 
    $query = "SELECT `id` FROM `achievements` WHERE `achieveID`=".$v['ID']." LIMIT 1"; 
    if ($result = mysqli_query($default, $query)) { 
     $row_cnt = mysqli_num_rows($result); 
     $row_cnt > 0 ? $parse = false : $parse = true; 
     mysqli_free_result($result); 
    } 
    $v['required'] == 'None' ? $req = $v['required'] : $req = json_encode($v['required'], JSON_FORCE_OBJECT); 
    if($parse) {       
     $result = mysqli_query($default, "INSERT INTO `achievements` VALUES (NULL, '".$v['cat']."', '".$v['ID']."', '".$v['title']."', '".$v['type']."', '".$v['factionD']."', '".$v['factionE']."', '".$v['text']."', '".$v['doneText']."', '".$v['points']."', '".$v['number']."', ".$req.", '".$v['rewards']."')") or die ('Unable to execute query. '. mysqli_error($default)); 
    } 
} 

我的代碼將一切都在罰款一樣,和做其他行,但是當它到達所需JSON數據的行(即當[「需要」] $ V不等於無)不插入它並給我一個錯誤。

Unable to execute query. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"0":"Into the Undertow","1":"Darkwater Abyss","2":"Primal Powers and Triton's Dr' at line 1 

的JSON(從JSON編碼)

{"0":"Into the Undertow","1":"Darkwater Abyss","2":"Primal Powers and Triton's Dread","3":"Stirring Interstellar Waves"} 

這似乎是雙引號引起的問題?

編輯

我重寫了我的代碼!感謝您的提示!

$insert = $default->prepare("INSERT INTO achievements (catID, achieveID, achieveName, achieveType, factionDominion, factionExiles, achieveText, achieveCText, achievePoints, achieveNum, achieveReq, achieveRew) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); 
$insert->bind_param("iissiissiiss", $cat, $id, $title, $type, $factionD, $factionE, $text, $doneText, $points, $number, $required, $rewards); 

foreach ($newArray as $k => $v) { 
    $query = "SELECT id FROM achievements WHERE achieveID=".$v['ID']." LIMIT 1"; 
    if ($result = $default->query($query)) { 
     $row_cnt = $result->num_rows; 
     $row_cnt > 0 ? $parse = false : $parse = true; 
    } 
    $v['required'] == 'None' ? $req = $v['required'] : $req = json_encode($v['required'], JSON_FORCE_OBJECT); 
    if($parse) {  
     $cat = $v['cat']; 
     $id = $v['ID']; 
     $title = $v['title']; 
     $type = $v['type']; 
     $factionD = $v['factionD']; 
     $factionE = $v['factionE']; 
     $text = $v['text']; 
     $doneText = $v['doneText']; 
     $points = $v['points']; 
     $number = $v['number']; 
     $required = $req; 
     $rewards = $v['rewards']; 
     $insert->execute(); 
    } 
} 
$default->close(); 

它的工作非常好,速度也非常快,幾秒鐘內就增加了2000多行!我很確定有一個更清晰的方式來寫它,但第一次使用準備!

+0

使用準備報表。它更安全。 – Jens

回答

2

你的問題就在這裏'".$v['number']."', ".$req.",

$req變量包含字符串,你需要用它在單引號

'".$v['number']."', '".$req."',

最好的辦法是使用準備語句來避免這些錯誤和SQL注入。

+0

謝謝,我剛剛發現我自己大聲笑...在第100次重新檢查我的代碼後! – Sickaaron