[eluser]Dyllon[/eluser]
You can try something like this, it's a quick, dirty and untested version of something I'm currently using.
Assumes your table contains the columns 'id' and 'position'
names model:
Code:
function moveName($id, $destination_id)
{
//Do some error checking
if ($id == $destination_id)
{
return FALSE;
}
//get destination row
$query = $this->db->getwhere('names', array('id'=> $destination_id));
if ($query->num_rows() == 0)
{
return FALSE;
}
else
{
$destination = $query->row();
}
//get departure row
$query = $this->db->getwhere('names', array('id'=>$id));
if ($query->num_rows() == 0)
{
return FALSE;
}
else
{
$departure = $query->row();
}
if ($departure->position > $destination->position)
{
$direction = 'up';
$new_position = $destination->position +1;
}
elseif ($departure->position < $destination->position)
{
$direction = 'down';
$new_position = $destination->position;
}
//Shift all affected names up or down
if ( ! $this->_shiftNames( $direction, $destination->position, $departure->position ) )
{
return FALSE;
}
//Move name from departure to destination
$this->db->where('id', $id);
return $this->db->update('names', array('position' => $new_position));
}
function _shiftNames($direction, $start, $stop)
{
switch ($direction)
{
case 'up':
$this->db->set('position', 'position +1', FALSE);
$this->db->where('position >', $start);
$this->db->where('position <', $stop);
break;
case 'down':
$this->db->set('position', 'position -1', FALSE);
$this->db->where('position <=', $start);
$this->db->where('position >', $stop);
break;
default:
return FALSE;
}
return $this->db->update('names');
}
In your controller:
Code:
//Move a name to a new location
function ajaxMove($id = null, $destination = null)
{
$json = array();
if (isset($id) && isset($destination))
{
$json['success'] = $this->names_model->moveName($id, $destination);
}
else
{
$json['success'] = FALSE;
}
$this->output->set_output( json_encode($json) );
}