2016-07-04 97 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(); 
    } 
}