A New Sorting Mechanism in Database

If one wants to add a field to record sorting order, following mechanism is recommended.

In HTML’s Select List or Option List, the positioning indication can be written as:

Before Item 1 – Order_Value is 0
Before Item 2 – Order_Value is 1

Then, the Sort_Order can be written into Database as Order_Value*2-1, which can be applied in both cases as new record or move existing record. By doing this, one can easily insert or move item. This is because in database this field is recorded as 0, 2, 4, 6... Of course, inserting or moving can be done once a time, followed by sorting.

Following is the example in PHP.

public function saveCateNew($order)
{ $orderNew = $order*2-1;
$query = sprintf( ' INSERT INTO CATES_SELF '
. ' (TITLE_1 '
. ' , SORT_ORDER '
. ' ) VALUES '
. ' ("%s" '
. ' , %d '
. ' ) '
, mysql_real_escape_string($this->title_1, $GLOBALS['DB'])
, $orderNew
);
mysql_query($query, $GLOBALS['DB']) or die("An error has ocured: ".mysql_error().":".mysql_errno());
$this->sortCate();
}

public function saveCateOld($order)
{ $orderNew = $order*2-1;
$query = sprintf( ' UPDATE CATES_SELF '
. ' SET TITLE_1 = "%s" '
. ' , SORT_ORDER = %d '
. ' WHERE ID_CATESELF = %d '
, mysql_real_escape_string($this->title_1, $GLOBALS['DB'])
, $orderNew
, $this->id_cateself
);
mysql_query($query, $GLOBALS['DB']) or die("An error has ocured: ".mysql_error().":".mysql_errno());
$this->sortCate();
}

function sortCate()
{ $query = sprintf( ' SELECT ID_CATESELF '
. ' FROM CATES_SELF '
. ' ORDER BY SORT_ORDER '
);
$result = mysql_query($query, $GLOBALS['DB']);
$index = 0;
while($row = mysql_fetch_assoc($result))
{ $id = $row['ID_CATESELF'];
$queryInner = sprintf( ' UPDATE CATES_SELF '
. ' SET SORT_ORDER = %d '
. ' WHERE ID_CATESELF = %d '
, $index
, $id
);
mysql_query($queryInner, $GLOBALS['DB']) or die("An error has ocured: ".mysql_error().":".mysql_errno());
$index = $index+2;
};
mysql_free_result($result);
}

No comments:

Post a Comment

Labels