根据给定的php数组重新排序MySql表行

时间:2016-07-04 15:28:04

标签: php mysql

我想根据给定的php数组重新排序表行。

$table = $_POST["table"];
$rlist = json_decode( $_POST['b'], true );

foreach ($rlist as $value) {
    $i = array_search($value, $rlist);
    $i+=1;
    echo "<div>" . $i . "</div>";
}

这很好用。结果是1 2 3 4 5 ...

可是:

foreach ($rlist as $value) {
   $i = array_search($value, $rlist);
   $i+=1;
   try {
    $stmt = $db->prepare('UPDATE ' . $table. ' SET sort = :sort WHERE title = :title') ;
    $stmt->execute(array(
    ':sort' => $i,
    ':title' => $value,
    ));
    exit;
    }
    catch(PDOException $e) {
    echo $e->getMessage();
    }
}

这不完全有效。排序列中的结果是:1 1 3 4 5 ...

2 个答案:

答案 0 :(得分:0)

这是否按预期工作?

foreach ($rlist as $iPos => $value) {

   try {
        $stmt = $db->prepare('UPDATE ' . $table. ' SET sort = :sort WHERE title = :title') ;
        $stmt->execute(array(
            ':sort' => $iPos + 1,
            ':title' => $value,
        ));
    }catch(PDOException $e) {
        echo $e->getMessage();
    }
}

答案 1 :(得分:0)

循环中有一个“exit”语句阻止它迭代。更正后的代码应为:

foreach ($rlist as $value) {
   $i = array_search($value, $rlist);
   $i+=1;
   try {
    $stmt = $db->prepare('UPDATE ' . $table. ' SET sort = :sort WHERE title = :title') ;
    $stmt->execute(array(
    ':sort' => $i,
    ':title' => $value,
    ));

    }
    catch(PDOException $e) {
    echo $e->getMessage();
    }
}