[eluser]Unknown[/eluser]
practically it very boring job and wasting time :-S even to just copy paste code like:
Code:
if(!$this->input->post('id') {
$data = array(
'title' => $this->input->post('title') ,
'name' => $this->input->post('name') ,
'date' => $this->input->post('date')
);
$this->db->insert('mytable', $data);
} else {
$data = array(
'title' => $this->input->post('title') ,
'name' => $this->input->post('name') ,
'date' => $this->input->post('date')
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
}
so i did something to cutoff the code.
usually field name in database is used as post variable name,
so here i do:
create some helper and add these function
Code:
// get column name
function get_table_fld($table){
$_this = & get_instance();
$sql = "show columns from $table ";
$res = $_this->db->query($sql);
$rows = $res->result();
foreach($rows as $r){
$fld[] = $r->Field;
}
$fld = implode(';',$fld);
return ($fld);
}
// match column name with post variable name
function post2data($str,$forced = true){
$_this = & get_instance();
$key = explode(';',$str);
foreach($key as $k){
if($forced){
if(!$_POST[$k]) continue;
} else {
if(!$_this->input->post($k)) continue;
}
$data[$k] = $_this->input->post($k);
}
return $data;
}
// storing data
// if the 'where' condition met, it automatically update
// otherwise it will insert
function store_data($table,& $data,$where){
$_this = & get_instance();
$result=0;
$sql = "select count(*) as cnt from $table where $where ";
$res = $_this->db->query($sql);
$row = $res->row();
if($row->cnt == 0) {
if($_this->db->insert($table,$data)) {
$data[$id] = mysql_insert_id();
$result=1;
}
} else {
$this->db->where($where,null,false);
if($_this->db->update($table,$data))
$result=1;
}
return $result;
}
so we can cutoff the code rather than write code like before to be just like
Code:
$tabledata = get_table_fld('my_table');
$data = post2data($tabledata);
if( store_data('my_table',$data,'id = '.$this->input->post('id'))){
# do some action here ...
}
it's a clean code, isn't it
and it's all same for all table
just
rename the table,
change
'where' statement
just that!
and no more boring and wasting time
;-)