Welcome Guest, Not a member yet? Register   Sign In
Inserting Blank db Record then Updating
#1

[eluser]Fielder[/eluser]
I was looking over the code I found in the Add Edit Views addon in the wiki, and wanted to get more explanation on a piece of code from it.

Code:
function Add($data){
  // Run query to insert blank row
  $this->db->insert('departments', array('department_id' => NULL) );
  // Get id of inserted record
  $id = $this->db->insert_id();
  // Now call the edit function to update the actual data for this new row now we have the ID
  return $this->Edit($id, $data);
}

function Edit($id, $data){
  $this->db->where('department_id', $id);
  $result = $this->db->update('departments', $data);
  // Return
  if($result){
    return $id;
  } else {
    return false;
  }
}

So, adding a new database entry is not really an Add in this code, rather it is an update of a blank database entry. Is that a good way of doing a new entry? Does it provide you with more efficient code or more flexibility for other things?
I thought it was an interesting way of adding records to the database instead of the $this->db->insert().
#2

[eluser]Thorpe Obazee[/eluser]
I wouldn't do something this way and it just wastes time to code.

Besides, having a lot of null fields is probably not a symptom of good table structure.
#3

[eluser]Dam1an[/eluser]
That has got to be painfully inefficient right?
I mean you do 3 queries (blank insert, fetch ID and update) instead of just the insert (and optionally getting the ID)

Also, as bargainph mentioned, if I was to do this for my tables, I would need to pass an entire null array, or have a load of nullable columns

The only potential reasoning I can think of for this approach is that you only have one worker method, and one accessor, instead of 2 worker methods (not that an intert is a lot of work... in fact, they're making it MORE work)




Theme © iAndrew 2016 - Forum software by © MyBB