I'm building a component which is about to be finalized, but there is a bit of code that I want to refactor. I think this code can be completed in one statement and I used more than 3 statements.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
foreach ($pks as $i => $pk)
{
//getting the sid from student table
$query->clear();
$query->select('sid')
->from('#__student')
->where('id = '.$pk);
$db->setQuery($query);
$sid = $db->loadResult();
$query->clear();
//fetching the data of old entry from log table using sid
$query->select('*')
->from('#__log')
->where('sid = '.$sid)
->where('pas= 0')
->where('stops=0');
$db->setQuery($query);
$obj=$db->loadObject('stdClass');
//updating the old entry in log table
$query->clear();
$query->update('#__log')
->set('pas = 1')
->where('sid = '.$sid)
->where('pas= 0')->where('stops=0');
$db->setQuery($query);
$db->execute();
//I'm doing this to know about is there at-least one row affected if not then we will not insert a new recorded
$count=$db->getAffectedRows();
//after setting pass to 1 we will ++ class by 1 and year by 1
$obj->class=$obj->class+1;
$obj->year=$obj->year+1;
if($count == 1)
{
$query->clear();
$query->insert('#__log')
->columns('class, year, sid, prmoted')
->values($obj->class.','.$obj->year.','.$sid.','. 1);
$db->setQuery($query);
$db->execute();
}
In this code, first I select the current student record from the #__log
table for next use. Then I update the same record and set pass
to 1
. Then using previously selected data, I insert a new record in same log table with class+1
and year+1
values.
I think this code can be highly refactored can any body help me?