保存新的div顺序以避免重复执行SQL查询

时间:2019-03-28 06:54:27

标签: 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次?

1 个答案:

答案 0 :(得分:1)

您需要使用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";