Generic fast coded PHP MySQL dynamic insert/update query creating table/fields named as variables if doesnt exists -
i'm looking way make mysql insert/update queries more dynamic , fast code since 1 need field in form (when example prototyping application). might dumb question.
my idea make insert or update if ids match, , if table/fields doesn't exists create 1 function dynamically.
<?php // $l set db-login stuff // creates , inserts $f[] = nf(1,'this_id_x'); // this_id_* prefix ids $f[] = nf('value yep',$fieldname_is_this2) $tbl_name = "it_didnt_exist"; nyakilian_fiq($l, $tbl_name, $f); // done! //this update on above $fieldname_is_this2 = "this updated"; $f[] = nf(1,'this_id_x'); $f[] = nf($fieldname_is_this2); // function takes variable name field name $tbl_name = "it_didnt_exist"; nyakilian_fiq($l, $tbl_name, $f); ?>
i have been using function success. doesn't add column against structure of mvc framework. try this:
public function save(databaseconnection &$db) { $properties = get_object_vars($this); $table = $this->gettablename(); // $cols = array(); // $values = array(); foreach ($properties $key => $value) { $cols[] = "`$key`"; $values[] = '"'.$value.'"'; if ($value != null) { $updatecols[] = "`$key`".' = "'.$value.'"'; } } $sql = 'insert '.$table.' ('.implode(", ", $cols).') values ('.implode(", ", $values).') on duplicate key update '.implode(", ", $updatecols); $stmnt = $db->prepare($sql); var_dump($stmnt); if ($stmnt->execute($values)) return true; return false; }
i have model abstract class extend child class each database table. function sits in model abstract. each child class contains public property [so can use pdo::fetchobject()] corresponds column name in table. if need create table on fly, add function child class so.
Comments
Post a Comment