2017-07-31 69 views
-1

我想更新我的MySQL表。當我輸入ID作爲數字時,但使用變量時,它不起作用。mysql查詢ID作爲變量不起作用

我想要做的是按列排序html表格的元素。

我有例如4列:

$colname = array("Column1", "Column2", "Column3", "Column4"); 

我從URL變量已經排序的元素的ID:

$strTaskIds = $_GET["taskIds"]; 
// for example: $strTaskIds = "3;1;32_4;5_6;36_34;7" 

現在我分割字符串成一個二維數組和更新MySQL表:

$arrTaskIds = explode("_", $strTaskIds); 

for($i = 0; $i < count($arrTaskIds); $i++) { 
    $arrIdsPerCol = explode(";", $arrTaskIds[$i]); 

    for($j = 0; $j < count($arrIdsPerCol); $j++) { 
     $sql = "UPDATE tasks SET col='$colname[$i]', rank=$j WHERE id=$arrIdsPerCol[$j]"; 
    } 

    if($conW->query($sql) === TRUE) { 
     $error = 0; 
    } else { 
     $error = 1; 
    } 
} 

當我編寫一個數字EG 7而不是變量$arrIdsPerCol[$j]它的作品。

寫作(int)$arrIdsPerCol[$j]也不起作用。

+3

[小博](http://bobby-tables.com/)說** [你的腳本是在對SQL注入攻擊的風險(http://stackoverflow.com/questions/60174 /如何-可以-I-防止-SQL注入功能於PHP)**。瞭解[MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)的[Prepared Statements](準備語句)(http://en.wikipedia.org/wiki/Prepared_statement)。即使** [轉義字符串](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)**是不安全的! – GrumpyCrouton

回答

0

我給你沒有錯誤信息的原因是沒有。它看起來像MySQL表沒有更新。
在我的代碼上演了很長時間之後,發現了這個問題。
我把query()代碼放在外部循環中。但我需要在內部循環。 問題解決了:

$arrTaskIds = explode("_", $strTaskIds); 
$error = 0; 

for($i = 0; $i < count($arrTaskIds); $i++) { 
    $arrIdsPerCol = explode(";", $arrTaskIds[$i]); 

    for($j = 0; $j < count($arrIdsPerCol); $j++) { 
    $sql = "UPDATE tasks SET col='$colname[$i]', rank=$j WHERE id=$arrIdsPerCol[$j]"; 
    if($conW->query($sql) === TRUE) { 
    } else { 
     $error = 1; 
    } 
    } 
}