这里发生了一些奇怪的事情,通常我不会有问题,或者我可能只是累了。但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 ['required']不等于none时)它不会插入它并给我错误。
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行!我很确定有一种更清晰的方式来编写它,但第一次使用prepare!
答案 0 :(得分:2)
您的问题在'".$v['number']."', ".$req.",
$req
变量包含字符串,您需要将其包装在单引号中
'".$v['number']."', '".$req."',
最好的选择是使用prepare语句来避免这些错误和SQL注入。
答案 1 :(得分:0)
您需要转义引号和特殊字符。查看mysqli_real_escape_string