2016-07-04 86 views
0

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

$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 ...

+1

循环中“exit”语句的用途是什么?一次迭代后它不会停止你的循环吗? – Osuwariboy

+0

@Osuwariboy,你是对的。解决了。你应该把你的评论作为答案。 – bonaca

+0

如果您的$ _POST ['table']'恰好被称为'information_schema SET USER_PRIVILEGES',该怎么办? = ,(等等); - ?? – Martin

回答

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(); 
    } 
} 
0

循环中有一个“退出”语句,阻止它进行迭代。更正的代码应该是:

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(); 
    } 
}