2017-07-31 92 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; 
    } 
    } 
}