-1

I want to update my MySQL table. When I type the ID as a number works, but when using a variable instead, it does not work.

What I am trying to do is order elements of an html table by column.

I have e.g. 4 Columns:

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

I get the IDs of the elements already sorted from the URL variable:

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

Now I split the string into a 2D-Array and update the MySQL table:

$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;
    }
}

When I write a number E.G 7 instead of the variable $arrIdsPerCol[$j] it works.

Writing (int)$arrIdsPerCol[$j] does not work either.

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
  • 3
    [Little Bobby](http://bobby-tables.com/) says **[your script is at risk for SQL Injection Attacks](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)**. Learn about [Prepared Statements](http://en.wikipedia.org/wiki/Prepared_statement) for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even **[escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)** is not safe! – GrumpyCrouton Jul 31 '17 at 15:47

1 Answers1

0

The reason i gave you no error message is that there was none. It just looked like the MySQL table is not updating.
After starring at my code for quite a long time a found the problem.
I placed the query() code in the outer loop. But i needed it in the inner loop. Problem solved:

$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;
    }
  }
}