Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to - sql update sort order after delete

Tags:

sql

php

mysql

The code below works fine but I'm wondering if there are alternative ways of handling this. Basically, after removing an entry, I need to update the sort order.

$sql = 'DELETE FROM `ee_blog_category` WHERE id = '.$category_id;
mysqli_query($con,$sql);
if(mysqli_error($con)){
    echo mysqli_error($con);
}
// update cat sort
$i = 1;
$sql = 'SELECT * FROM `ee_blog_category` ORDER BY `sort`';
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)){
    $sql1 = 'UPDATE `ee_blog_category` SET `sort` = '.$i.' WHERE `id` = '.$row['id'];
    mysqli_query($con,$sql1);
    $i++;
}
like image 844
drooh Avatar asked Jun 05 '26 01:06

drooh


1 Answers

Yes, there is a different (I think better) way:

  1. get the sort value of the deleted item (of course before you delete it).
  2. Update all the items which have a greater sort value with sort=sort-1

In your case this would be something like:

$sql = "Select sort from ee_blog_category where id=$category_id";
// execute, fetch, catch errors...
$sort_original = $row['sort'];

// now update all the others
$sql = "UPDATE ee_blog_category SET sort=sort-1 where sort > $sort_original"; // maybe add a filter here (by group f.e.)
// execute, check for errors.

NOTE:
You could be open to sql-injection.
Better use prepared statements!

like image 112
Jeff Avatar answered Jun 07 '26 18:06

Jeff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!