我試圖將jquery可排序功能併入我的網站,並保存在數據庫中的位置給我各種各樣的頭痛......我一直在爲此奮鬥3天現在,我似乎無法正確地完成這項工作。jquery可排序保存到數據庫不能正常工作
就目前而言,它將位置保存到數據庫中,但不保存您期望的順序或位置。意思是,如果我將位置0中的項目移動到位置1,它將以不同的順序在數據庫中保存位置。看看一個真人版here。
這裏是我的代碼...
index.php文件:
<div id="container">
<?php
require_once 'conn.php';
$q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
$result = mysqli_query($db, $q);
if ($result->num_rows > 0) {
while($items = $result->fetch_assoc()) {
?>
<div id='sort_<?php echo$items['position'] ?>' class='items'>
<span>☰</span> <?php echo$items['description'] ?>
</div>
<?php
}
}
?>
</div>
js.js文件:
$("#container").sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var itId = 3;
var post = $(this).sortable('serialize');
$.ajax({
type: 'POST',
url: 'save.php',
data: {positions: post, id: itId },
dataType: 'json',
cache: false,
success: function(output) {
// console.log('success -> ' + output);
},
error: function(output) {
// console.log('fail -> ' + output);
}
});
}
});
$("#container").disableSelection();
save.php文件:
require_once('conn.php');
$itId = $_POST['id'];
$orderArr = $_POST['positions'];
$arr = array();
$orderArr = parse_str($orderArr, $arr);
$combine = implode(', ', $arr['sort']);
$getIds = "SELECT id FROM items WHERE groupId = '$itId' ";
$result = mysqli_query($db, $getIds);
foreach($arr['sort'] as $a) {
$row = $result->fetch_assoc();
$sql = " UPDATE items
SET position = '$a'
WHERE id = '{$row['id']}' ";
mysqli_query($db, $sql);
}
echo json_encode(($arr['sort']));
任何人都可以請指出我要去哪裏錯了 這個?
預先感謝您。
塞爾
您的代碼很容易受到[** SQL注入**] (https://en.wikipedia.org/wiki/SQL_injection)攻擊。您應該通過[** mysqli **](https://secure.php.net/manual/en/mysqli.prepare.php)或[** PDO **](https ://secure.php.net/manual/en/pdo.prepared-statements.php)驅動程序。 [**這篇文章**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)有一些很好的例子。 –
查看** serialize **函數(「序列化鍵」)http://api.jqueryui.com/sortable/#method-serialize或(「toArray」)http://api.jqueryui。 COM /可排序/#方法-指定者。並注意SQL注入。 – Richard
@AlexHowansky我瞭解Alex。我只是試圖在繼續進行安全性前完成這項工作。除了這個例子,這個數據庫絕對沒有。 – Sergio