<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/