I am trying to use the keys of an array as values to update a column in my database. The column in question is the sort order for the rows.
Lets say the sort column values for each row are 1, 3, 5, 8, 9, 10, 12.
When the code is executed this is to be updated to read 1, 2, 3, 4, 5, 6, 7.
My code below does what I am trying to achieve when I echo the values however I am having a problem with the update query.
$sql = "SELECT asset, sort FROM portfolio ORDER BY sort ASC";
$query = mysqli_query($conn, $sql);
$i = 0;
while ($row = mysqli_fetch_assoc($query)){
$asset[$i] = $row['asset'];
$sort[$i] = $row['sort'];
$new_sort = $i+1;
$assets = implode(',', $asset);
$update_sql = "UPDATE portfolio SET sort='$new_sort' WHERE asset IN ('$assets')";
mysqli_query($conn, $update_sql);
$i++;
}
Using the following only the first row is being updated:
$assets = implode(',', $asset);
Using the following all rows are being updated, however they are all being set to the last value, in this example it would be 7.
$assets = join("','",$asset);
UPDATE: $assets is a string, an example would be google,yahoo,apple etc..
Any ideas where I am going wrong? Many Thanks.
$assetsinteger or string?$assets = implode("','", $asset); $update_sql = "UPDATE portfolio SET sort='$new_sort' WHERE asset IN ('$assets')";try this