使用MySQL表中的SQL Update列的数组到列行

使用MySQL表中的SQL Update列的数组到列行

问题描述:

I have array named olmali

$olmali = $_POST['result'];

And

print_r($olmali);
Result is below:

Array ( 
    [0] => 1
    [1] => 1
    [2] => 20
    [3] => 2 
    [4] => 3
    [5] => 5
    [6] => 6 
    [7] => 7 
    [8] => 9 
    [9] => 8 
    [10] => 10
    [11] => 11
    [12] => 13
    [13] => 12 
    [14] => 12
    [15] => 14 
    [16] => 15
    [17] => 16
    [18] => 17
    [19] => 17
    [20] => 19
    [21] => 20
)

I want to use SQL UPDATE command and I expect:

id        test
1          1
2          1
3          20
4          2
5          3
6         ....and goes on

How can I resolve this problem? Is there any way and how can I do it. PHP array to column row in MySQL table with UPDATE SQL command like that

</div>

I would suggest to start from the end with a for loop and reassign every key with a value +1. Then, you just have to remove the first index of the array with unset(). See the code below.

$olmali = [
  0 => 1,
  1 => 1,
  2 => 20,
  3 => 2,
  4 => 3,
  5 => 5,
  6 => 6,
  7 => 7,
  8 => 9,
  9 => 8,
  10 => 10,
  11 => 11,
  12 => 13,
  13 => 12,
  14 => 12,
  15 => 14,
  16 => 15,
  17 => 16,
  18 => 17,
  19 => 17,
  20 => 19,
  21 => 20
];

for($i = count($olmali); $i > 0; $i--) {
  $olmali[$i] = $olmali[$i - 1];
}

unset($olmali[0]);

print_r($olmali);

Output:

Array ( [1] => 1 [2] => 1 [3] => 20 [4] => 2 [5] => 3 [6] => 5 [7] => 6 [8] => 7 [9] => 9 [10] => 8 [11] => 10 [12] => 11 [13] => 13 [14] => 12 [15] => 12 [16] => 14 [17] => 15 [18] => 16 [19] => 17 [20] => 17 [21] => 19 [22] => 20 )

Assuming

    $myArray = array ( 
        [0] => 1
        [1] => 1
        [2] => 20
        [3] => 2 
        [4] => 3
        [5] => 5
        [6] => 6 
        [7] => 7 
        [8] => 9 
        [9] => 8 
        [10] => 10
        [11] => 11
        [12] => 13
        [13] => 12 
        [14] => 12
        [15] => 14 
        [16] => 15
        [17] => 16
        [18] => 17
        [19] => 17
        [20] => 19
        [21] => 20
    );

then once you have a db connection using a PDO prepare binding and execute

$stmt = $conn->prepare("Update my_tabe 
            set my_column  = :my_value 
            where my_id_comn  = :my_id +1" );
$stmt->bindParam(':my_value', $value);
$stmt->bindParam(':my_id', $key);

foreach ($myArray as $key => $value){
      $stmt->execute();
}