javascript - 保存新的 div 顺序避免重复 sql 查询

标签 javascript php mysql

<div class="artitle" data-id=1>lorem</div>
<div class="artitle" data-id=2>ipsum</div>
//and so on - about 500 divs

我使用 javascript 对 div 上下重新排序,需要将这个新顺序保存在数据库中(ind 列)。

let ids = $.map($('.artitle'), (e) => $(e).data('id')).join(',');
let inds = $.map($('.artitle'), (e) => $(e).index()).join(',');
//$.post... - send the variables on remote server

php

$aids = explode(',', $ids);
$ainds = explode(',', $inds);
foreach($aids as $key=>$val){
    $sql = "update arts set ind = :aind where id = :aid";
    $st = $db->prepare($sql);
    $st->execute([
        ":aind" => $ainds[$key],
        ":aid" => $val
    ]);
}

它有效,但是否有更好的方法 - 避免重复 sql 查询 500 次?

最佳答案

您需要使用 PHP 构建单个 mysql 查询并使用 INSERT INTO mysql 功能(multiple updates in one query 更新多行,下面是您应该如何做(我还没有使用准备好的声明,这是为了让你弄清楚,因为现在你已经知道如何以编程方式构建查询):

PHP

$aids = explode(',', $ids);
$ainds = explode(',', $inds);

$timeStart = microtime(true);

$sqlQuery = 'INSERT INTO arts (id,ind) ';

foreach($aids as $key=>$val){

    $sqlQuery .= "VALUES ($val,$ainds[$key]),";

}

#REMOVE THE LAST COMA(,)
$sqlQuery = substr($sqlQuery, 0, -1);

$sqlQuery .= 'ON DUPLICATE KEY UPDATE id=VALUES(id),ind=VALUES(ind);';

#RUN THIS AS REQUIRED, YOU GOT YOUR DYNAMICALLY GENERATED MYSQL MULTIPLE UPDATE STATEMENT#
#$sqlQuery;

$timeEnd = microtime(true);
$time = $timeEnd - $timeStart;

echo "Took $time seconds\n";

关于javascript - 保存新的 div 顺序避免重复 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55391736/

相关文章:

javascript - 如何对 mouseenter 上的元素执行操作?

php - 如何正确拦截 PHP 中的 404 错误?

php - 在插入数据 (PHP) 中调用 bool 值的成员函数 bind_param()

PHP 发布值但数据库未更新

Mysql:Order By 返回错误

javascript - Kyle Simpson 的 YDKJS 中的动态范围和 `this`

javascript - 同时从不同列表中选择项目

javascript - 如何使用多个对象创建球体

php - 在 ubuntu 上的 php 5.4.9 中使用 mysql_connect 清空 $_POST,Globals

mysql - JDBCExceptionReporter [错误] 字段 'id' 没有默认值