MYSQL 根据 jquery 可排序的特定顺序更新

MYSQL update based on certain order from jquery sortable

我正在使用 jquery sortable 并尝试将这些项目的位置保存到 mysql table 的名为 "position" 的行中。我似乎无法让它们正确地到达 save/update。 jquery 方面一切正常,只是 php 更新功能。现在它将位置行保存为 3,我明白为什么了。我似乎无法理解如何正确地做到这一点。

这是我为PHP准备的:

$id = $_POST['id'];
$arr = $_POST['positions'];

foreach($arr as $r) {
   $sql = " UPDATE items
            SET   position = '$r'
            WHERE groupId = '$id' ";
}

Table 结构/所需输出:

id | groupId | position
----------------------------
3    10       0
6    8        -
8    10       3
10   5        -
15   10       2
18   10       1

jQuery 文件:

$("#items").sortable({
      update: function() {
         var invId = $("input[name='deleteId']").val();
         var post = $(this).sortable('serialize');

         $.ajax({
            type: 'POST',
            url: 'file.php',
            data: { positions: post, id: invId },
            dataType: 'JSON',
            cache: false,
            success: function(output) {
               console.log('success');
            },
            error: function(output) {
               console.log('fail ');
            }
         });
      }
   });

谢谢。

您的查询在每次循环中都会用 groupId = 10 更新 所有 行,因此最后它们都将包含数组最后一个元素的值。

您需要编写一个查询,为 table 中的每个匹配行获取一个行号,然后仅更新该行。您可以使用用户定义的变量来增加行号。

UPDATE items AS i1
JOIN (SELECT id, @rownum := rownum + 1 AS rownum
      FROM (SELECT id
            FROM items
            WHERE groupId = '$id'
            ORDER BY id) AS i
      CROSS JOIN (SELECT @rownum := 0) AS var) AS i2
ON i1.id = i2.id
JOIN (SELECT 1 AS target, 0 AS val
      UNION ALL
      SELECT 2, 3
      UNION ALL
      SELECT 3, 2
      UNION
      SELECT 4, 1) AS newpos
ON newpos.target = i2.rownum
SET i1.position = newpos.val

我想我可能遗漏了一些东西,但也许您应该根据与特定组 ID 匹配的 ID 更新项目 table。像这样:

$id = 10;
$arr = ('0', '3', '2', '1');

$searchId = "SELECT id FROM items WHERE groupId = '$id'";
$result = $db->query($searchId);

foreach($arr as $r) {
   $row = $result->fetch_assoc();
   $sql = " UPDATE items
            SET   position = '$r'
            WHERE id = '{$row['id']}' ";
}

我假设你使用 mysqli 连接到你的数据库。

jQuery 可排序应该已经 post 数据,其中值是行 ID,键是顺序。这样,您就可以执行 foreach 循环。假设以下数据:

//$_POST (use chrome inspector to see what post data is being sent)
//positions[] = 3
//positions[] = 18  
//positions[] = 15  
//positions[] = 8  

// note: use a prepared statement, this is just to demonstrate the query.
foreach($_POST['positions'] as $i => $id) {
    $db->query('update table set position = ? where id = ? ',array($i, $id));
}

如果有人遇到类似问题来到这里,这对我有用。

更新PHP文件:

$isNum = false;

foreach( $_POST['sort'] as $key => $value ) {
    if ( ctype_digit($value) ) {
        $isNum = true;
    } else {
        $isNum = false;
    }
}

if( isset($_POST) && $isNum == true ){
    require_once('con.php');
   $orderArr = $_POST['sort'];
    $order = 0;
    if ($stmt = $db->prepare(" UPDATE items SET position = ? WHERE id=? ")) {
        foreach ( $orderArr as $item) {
            $stmt->bind_param("ii", $order, $item);
            $stmt->execute();
            $order++;
        }
        $stmt->close();
    }
    echo json_encode(  $orderArr );
    $db->close();
}

JQUERY 可排序文件:

var sortable = $('#items');
   sortable.sortable({
      opacity: 0.325,
      tolerance: 'pointer',
      cursor: 'move',
      update: function(event, ui) {
         var post_data = sortable.sortable('serialize');

         $.ajax({
            type: 'POST',
            url: 'save.php',
            data: post_data,
            dataType: 'json',
            cache: false,
            success: function(output) {
               console.log('success -> ' + output);
            },
            error: function(output) {
               console.log('fail -> ' + output);
            }
         });

      }
   });
   sortable.disableSelection();