我试图将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