insert() public static méthode

public static insert ( )
 public function save($POST)
 {
     $db = new DB();
     $ref = "TF" . date("dmyhis");
     //        for($i = 0; $i < count($POST); $i++){
     //            if(count($POST[$i]) > 1)
     //                $type = "radio";
     //            else
     //                $type = "text";
     //            $sql = "INSERT INTO forms (question, ref, user_id, type) VALUES ('". $POST[$i][0] ."','". $ref ."', '1','". $type ."')";
     //            $last_id = $db->insert($sql);
     //            for($j = 0; $j < count($POST[$i]); $j++){
     //                $sql = "INSERT INTO choices (form_id, choice) VALUES ('". $last_id . "', '". $POST[$i][$j] . "')";
     //                $db->insert($sql);
     //            }
     //        }
     $sql = "INSERT INTO topics (topic, create_dt) VALUES ('" . $POST["topic"] . "', now())";
     $last_topic_id = $db->insert($sql);
     for ($i = 0; $i < count($POST["data"]); $i++) {
         $last_from_id = 0;
         if (count($POST["data"][$i]) > 1) {
             $sql = "INSERT INTO froms (question) VALUES ('" . $POST["data"][$i][0] . "')";
             $last_from_id = $db->insert($sql);
         }
         $start = $last_from_id == 0 ? 0 : 1;
         for ($j = $start; $j < count($POST["data"][$i]); $j++) {
             $sql = "INSERT INTO questions (question, from_id, topic_id) VALUES ('" . $POST["data"][$i][$j] . "', '" . $last_from_id . "', '" . $last_topic_id . "')";
             $db->insert($sql);
         }
     }
     $response["status"] = 0;
     $response["msg"] = "Success";
     echo json_encode($response);
 }
Exemple #2
0
 public function test_insert()
 {
     $dummy_data = $this->dummy_stream_data();
     $dummy_data['meta'] = $this->dummy_meta_data();
     $stream_id = $this->db->insert($dummy_data);
     $this->assertNotFalse($stream_id);
     $this->assertGreaterThan(0, $stream_id);
     $this->assertEquals(0, did_action('wp_stream_record_insert_error'));
     $this->assertGreaterThan(0, did_action('wp_stream_record_inserted'));
     global $wpdb;
     // Check that records exist
     $stream_result = $wpdb->get_row("SELECT * FROM {$wpdb->stream} WHERE ID = {$stream_id}", ARRAY_A);
     $this->assertNotEmpty($stream_result);
     foreach ($this->dummy_stream_data() as $dummy_key => $dummy_value) {
         $this->assertArrayHasKey($dummy_key, $stream_result);
         $this->assertEquals($dummy_value, $stream_result[$dummy_key]);
     }
     // Check that meta exists
     $meta_result = $wpdb->get_results("SELECT * FROM {$wpdb->streammeta} WHERE record_id = {$stream_id}", ARRAY_A);
     $this->assertNotEmpty($meta_result);
     $found_all_keys = true;
     foreach ($meta_result as $meta_row) {
         $key = $meta_row['meta_key'];
         $value = $meta_row['meta_value'];
         if (!isset($dummy_data['meta'][$key]) || $value !== $dummy_data['meta'][$key]) {
             $found_all_keys = false;
         }
     }
     $this->assertTrue($found_all_keys);
 }
Exemple #3
0
 /**
  * Membuat record baru.
  *
  * @return boolean
  */
 public function create($data = [])
 {
     try {
         $this->db->insert($this->table, $data);
         return true;
     } catch (Exception $e) {
         die($e->getMessage);
     }
 }
Exemple #4
0
 function login()
 {
     $accessToken = Url::get('accessToken', '');
     $login_info = json_decode(file_get_contents('http://ids.cpvm.vn/services/api/users/check_open_user.php?o=' . $accessToken . '&t=2'));
     if ($login_info->s) {
         $token = $login_info->v->t;
         //Lay thong tin user theo token
         $info = json_decode(file_get_contents('http://ids.cpvm.vn/services/api/users/userinfo.php?t=' . $token));
         if ($info->s) {
             $u = $info->v->u;
             $user = User::getUserById($u->id);
             if (!$user) {
                 // user chua co trong db => clone
                 $data = array('id' => $u->id, 'user_name' => $u->un, 'full_name' => $u->fn, 'avatar_url' => $u->av);
                 $id = DB::insert('account', $data);
             } else {
                 DB::update('account', array('full_name' => $u->fn), 'id=' . $u->id);
             }
             $u->t = $token;
             //dang nhap
             User::LogIn2((array) $u);
             $_SESSION['token'] = $token;
             echo 1;
         } else {
             echo 0;
         }
     } else {
         echo 0;
     }
     exit;
 }
Exemple #5
0
 /**
  * update account levels
  *
  * @param integer $account_id
  * @param array $data_level
  * @return boolean
  */
 public function updateLevels($account_id = '', $data_level = array())
 {
     // delete not exists level
     $lvls = static::query()->where('account_id', $account_id);
     if ($lvls->count() > 0) {
         foreach ($lvls->get() as $lvl) {
             if (!in_array($lvl->level_group_id, $data_level)) {
                 \DB::delete(static::$_table_name)->where('account_id', $account_id)->where('level_id', $lvl->level_id)->execute();
             }
         }
     }
     unset($lvls, $lvl);
     // update or insert fields
     if (is_array($data_level) && !empty($data_level)) {
         foreach ($data_level as $level_group_id) {
             $result = \DB::select()->from(static::$_table_name)->where('account_id', $account_id)->where('level_group_id', $level_group_id)->execute();
             if (count($result) <= 0) {
                 // not exists, use insert.
                 \DB::insert(static::$_table_name)->set(['account_id' => $account_id, 'level_group_id' => $level_group_id])->execute();
             }
             unset($result);
         }
     }
     // clear cache
     \Extension\Cache::deleteCache('model.accountLevelPermission-checkLevelPermission-' . \Model_Sites::getSiteId(false));
     return true;
 }
Exemple #6
0
 function on_submit()
 {
     $email_list = Url::get('email_list');
     $count = 0;
     if ($email_list) {
         $arr = explode("\n", $email_list);
         $arr_tmp = array();
         $email_list = '';
         if ($arr) {
             foreach ($arr as $email) {
                 $email = str_replace(array(chr(13), chr(10)), '', stripslashes($email));
                 if (eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\\.[A-Z]{2,6}\$", $email) && !isset($arr_tmp[$email])) {
                     $email_list .= ($email_list ? "\n" : '') . $email;
                     $arr_tmp[$email] = 1;
                     $count++;
                 }
             }
         }
     }
     $this->email_list = array('email_list' => addslashes($email_list), 'time' => TIME_NOW, 'time_modify' => TIME_NOW);
     $this->checkFormInput('Danh sách email', 'email_list', $email_list, 'str', true, '', 1);
     if ($count > 50) {
         $this->setFormError('', "Bạn đã nhập vào {$count} email, số mail nhập vào phải <=50!");
     }
     if (!$this->errNum) {
         $id = DB::insert('spam_mail', $this->email_list);
         if ($id) {
             Url::redirect_current(array('cmd' => 'email_list'));
         } else {
             $this->setFormError('', 'Không cập nhật được CSDL!');
         }
     }
 }
Exemple #7
0
    function on_submit()
    {
        $email = Url::get('email');
        $this->checkFormInput("Emal", 'email', $email, 'email', true);
        if (!$this->errNum) {
            if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']) {
                $referer = $_SERVER['HTTP_REFERER'];
            } else {
                $referer = $_SERVER['REQUEST_URI'];
            }
            $email = Url::get('email');
            if ($email != '') {
                if (!DB::select('news_letter_email', 'email="' . $email . '"')) {
                    DB::insert('news_letter_email', array('email' => $email, 'time_add' => TIME_NOW));
                }
                AZNet::$extraFooter .= '<script>
										alert("Đăng ký nhận bản tin thành công, cảm ơn bạn đã sử dụng dịch vụ!"); 				
										window.location = "' . $referer . '";
								 	</script>';
                return;
            }
            Url::redirect_url($referer);
        } else {
            AZNet::$extraFooter .= '<script>
										alert("Email bạn nhập không đúng định dạng!"); 				
										document.NewsLetterForm.email.focus(); 
										document.NewsLetterForm.email.select();
								 	</script>';
            return;
        }
    }
 public function insert($tid, $data, $return_insert_id = false, $replace = false, $silent = false)
 {
     if ($this->_allowmem) {
         $this->store_cache($tid, $data);
     }
     return DB::insert($this->_table, $data, $return_insert_id, $replace, $silent);
 }
	function viewthread_updatelog() {
		
		//初始化参数
		global $_G;
		$select_fid = $_G ['cache'] ['plugin'] ["bullmarket_myfootprints"] ["select_forumd"];
		//免费版不允许板块未设置,只支持一个版块
		if ($select_fid!=$_G['fid']) {
			return;
		}
		$uid = $_G ['uid'];
		if (! $uid) {
			return;
		}
		$tid = intval ( $_GET ['tid'] );
		if ($tid <= 0) {
			return;
		}
		//为了降低按天数分组时执行sql多损耗的时间,这里将day与time同时录入数据库(如果只存time而不存day,将会使得查询需要浪费更多的时间,大量损耗性能)。
		$day = date ( "Y-m-d", time () );
		$time = date ( "Y-m-d H:i:s", time () );
		$logarray = array ("uid" => $uid, "tid" => $tid, "day" => $day );
		if ($this->_dateisexist ( $logarray )) {
			$logarray ["time"] = $time;
			DB::insert ( "bullmarket_myfootprints_viewlog", $logarray );
		}
	}
 function install()
 {
     //bind password
     $password = post("adminpassword1");
     //create important vars
     $salt = rand(0, 99999);
     $md5_password = md5($salt . $password);
     DB::query("DROP TABLE IF EXISTS " . DB_PREFIX . "user");
     DB::query("CREATE TABLE " . DB_PREFIX . "user(\r\n                user_id int(11) NOT NULL AUTO_INCREMENT,\r\n                name varchar(90) NOT NULL,\r\n                salt int(5) NOT NULL default '0',\r\n                password varchar(32) NOT NULL default '0',\r\n                email varchar(255) NOT NULL,\r\n                last_ip varchar(255) NOT NULL default '127.0.0.1',\r\n                data_login int(15) NULL,\r\n                status int(1) NOT NULL default 1,\r\n                activation_code varchar(40) NULL,\r\n                lang_id varchar(2) NOT NULL default 'EN',\r\n                PRIMARY KEY (user_id)\r\n                ) ENGINE=MyISAM");
     DB::insert(DB_PREFIX . "user", array("name" => post("adminname"), "salt" => "{$salt}", "password" => "{$md5_password}", "email" => post("adminemail", FILTER_SANITIZE_EMAIL), "status" => 3));
     DB::query("DROP TABLE IF EXISTS " . DB_PREFIX . "user_where_is");
     DB::query("CREATE TABLE " . DB_PREFIX . "user_where_is ( \r\n            user_where_is_id int(11) NOT NULL AUTO_INCREMENT,\r\n            user_id int(11) NOT NULL,\r\n            guest_id int(11) NOT NULL,\r\n            ip varchar(20) NOT NULL default '127.0.0.1',\r\n            name varchar(90) NOT NULL,\r\n            sid varchar(32) NOT NULL,\r\n            url varchar(255) NOT NULL,\r\n            id int(11) NOT NULL,\r\n            file varchar(255) NOT NULL,\r\n            os varchar(255) NOT NULL,\r\n            browser varchar(255) NOT NULL,\r\n            time int(15) NOT NULL , \r\n            time_first_click int(15) NOT NULL,\r\n            country_code varchar(2) NOT NULL,\r\n            country_name varchar(90) NOT NULL,\r\n            region_code varchar(15) NOT NULL,\r\n            region_name varchar(255) NOT NULL,\r\n            city_name varchar(255) NOT NULL,\r\n            zip varchar(20) NOT NULL,\r\n            latitude varchar(55) NOT NULL,\r\n            longitude varchar(55) NOT NULL,\r\n            timezone_name varchar(255) NOT NULL,\r\n            gmt_offset varchar(255) NOT NULL,\r\n            PRIMARY KEY (user_where_is_id)\r\n            ) ENGINE=MyISAM");
     DB::query("DROP TABLE IF EXISTS " . DB_PREFIX . "usergroup");
     DB::query("CREATE TABLE " . DB_PREFIX . "usergroup(\r\n            group_id int(11) NOT NULL AUTO_INCREMENT,\r\n            parent_id int(11) NOT NULL,\r\n            name varchar(255) NOT NULL,\r\n            position int(11) NOT NULL,\r\n            nuser int(11) NOT NULL,\r\n            PRIMARY KEY (group_id)\r\n            ) ENGINE=MyISAM");
     DB::query("DROP TABLE IF EXISTS " . DB_PREFIX . "usergroup_user");
     DB::query("CREATE TABLE " . DB_PREFIX . "usergroup_user(\r\n            group_id int(11) NOT NULL,\r\n            user_id int(11) NOT NULL,\r\n            PRIMARY KEY (group_id , user_id)\r\n            ) ENGINE=MyISAM");
     DB::query("DROP TABLE IF EXISTS " . DB_PREFIX . "user_localization");
     DB::query("CREATE TABLE " . DB_PREFIX . "user_localization(\r\n            user_localization_id int(11) NOT NULL AUTO_INCREMENT,\r\n            ip varchar(20) NOT NULL DEFAULT '127.0.0.1',\r\n            sid varchar(32) NOT NULL,\r\n            user_id int(11) NOT NULL,\r\n            guest_id int(11) NOT NULL,\r\n            name varchar(90) NOT NULL,\r\n            url varchar(255) NOT NULL,\r\n            id int(11) NOT NULL,\r\n            file varchar(255) NOT NULL,\r\n            os varchar(255) NOT NULL,\r\n            browser varchar(255) NOT NULL,\r\n            time int(15) NOT NULL,\r\n            time_first_click int(15) NOT NULL,\r\n            country_code varchar(2) NOT NULL,\r\n            country_name varchar(90) NOT NULL,\r\n            region_code varchar(15) NOT NULL,\r\n            region_name varchar(255) NOT NULL,\r\n            city_name varchar(255) NOT NULL,\r\n            zip varchar(20) NOT NULL,\r\n            latitude varchar(55) NOT NULL,\r\n            longitude varchar(55) NOT NULL,\r\n            timezone_name varchar(255) NOT NULL,\r\n            gmt_offset varchar(255) NOT NULL,\r\n            PRIMARY KEY (user_localization_id)\r\n            )");
     $querys = DB::get_executed_query();
     $html_message = '<br /><strong>Install Complete!!!<br /></strong> Please Delete: <br /><strong>' . CONTROLLERS_DIR . 'install
         </strong><br />Please read next steps in the "Install-notes" <br />';
     if ($querys == 11) {
         echo draw_msg($html_message, INFO, true);
     } else {
         echo draw_msg("ERROR", ERROR, true);
     }
 }
Exemple #11
0
 public function save($isNewUser = false)
 {
     //create a new database object.
     $db = new DB();
     $username = mysql_real_escape_string($this->username);
     $email = mysql_real_escape_string($this->email);
     $firstName = mysql_real_escape_string($this->firstName);
     $lastName = mysql_real_escape_string($this->lastName);
     $link = mysql_real_escape_string($this->link);
     $blog = mysql_real_escape_string($this->blog);
     //if the user is already registered and we're
     //just updating their info.
     if (!$isNewUser) {
         //set the data array
         $data = array("username" => "'{$username}'", "password" => "'{$this->hashedPassword}'", "email" => "'{$email}'", "firstName" => "'{$firstName}'", "lastName" => "'{$lastName}'", "link" => "'{$link}'", "blog" => "'{$blog}'");
         //update the row in the database
         $db->update($data, 'users', 'id = ' . $this->id);
     } else {
         //if the user is being registered for the first time.
         $data = array("username" => "'{$username}'", "password" => "'{$this->hashedPassword}'", "email" => "'{$email}'", "link" => "'{$link}'", "blog" => "'{$blog}'", "firstName" => "'{$firstName}'", "lastName" => "'{$lastName}'", "join_date" => "'" . date("Y-m-d H:i:s", time()) . "'");
         $this->id = $db->insert($data, 'users');
         $this->joinDate = time();
     }
     return true;
 }
 function addEntry()
 {
     $user_id = $_GET['user_id'];
     $amt = $_GET['amt'];
     $raffle_id = $_GET['raffle_id'];
     DB::insert('raffle_entries', array("user_id" => $user_id, "entry_date" => date("m/d/Y"), "raffle_id" => $raffle_id, "entry_amount" => $amt));
 }
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     //
     DB::table('jabatan')->delete();
     $sql = "INSERT INTO `jabatan` (`id`, `nama_jabatan`, `created_by`) VALUES\n\t\t\t(1,\t'Kepala Proyek Indarung VI', '1'),\n\t\t\t(2,\t'General Manager', '1'),\n\t\t\t(3,\t'Staff DPD', '1'),\n\t\t\t(4,\t'Senior Manager', '1'),\n\t\t\t(5,\t'Manager', '1'),\n\t\t\t(6,\t'Kepala Urusan', '1'),\n\t\t\t(7,\t'Karyawan', '1'),\n\t\t\t(8,\t'PKWT Profesional', '1'),\n\t\t\t(9,\t'PKWT Biasa', '1'),\n            (10, 'Tamu Perusahaan', '1')";
     DB::insert($sql);
 }
 public function insert($tableid, $data, $return_insert_id = false, $replace = false, $silent = false)
 {
     if (!$data) {
         return;
     }
     return DB::insert($this->_get_table($tableid), $data, $return_insert_id, $replace, $silent);
 }
 /**
  * Run the migrations.
  *
  * @return void
  */
 public function up()
 {
     $json = '[
     {"id":1,"name":"\\u4e2d\\u56fd\\u5de5\\u5546\\u94f6\\u884c","status":1,"logo":"gongshang","home":"http:\\/\\/www.icbc.com.cn","alias":"ICBC","sort":5},
     {"id":2,"name":"\\u652f\\u4ed8\\u5b9d","status":1,"logo":"zhifubao","home":"https:\\/\\/auth.alipay.com","alias":"ALIPAY","sort":18},
     {"id":3,"name":"\\u8d22\\u4ed8\\u901a","status":1,"logo":"caifutong","home":"http:\\/\\/www.tenpay.com\\/","alias":"TENPAY","sort":19},
     {"id":4,"name":"\\u4e2d\\u56fd\\u519c\\u4e1a\\u94f6\\u884c","status":1,"logo":"nongye","home":"http:\\/\\/www.abchina.com","alias":"ABC","sort":6},
     {"id":5,"name":"\\u4e2d\\u56fd\\u4ea4\\u901a\\u94f6\\u884c","status":1,"logo":"jiaotong","home":"http:\\/\\/www.bankcomm.com","alias":"BCM","sort":7},
     {"id":6,"name":"\\u4e2d\\u56fd\\u5efa\\u8bbe\\u94f6\\u884c","status":1,"logo":"jianshe","home":"http:\\/\\/www.ccb.com","alias":"CCB","sort":8},
     {"id":7,"name":"\\u62db\\u5546\\u94f6\\u884c","status":1,"logo":"zhaoshang","home":"http:\\/\\/www.cmbchina.com\\/","alias":"CMB","sort":14},
     {"id":8,"name":"\\u4e2d\\u56fd\\u94f6\\u884c","status":1,"logo":"zhongyin","home":"http:\\/\\/www.boc.cn\\/","alias":"BOC","sort":15},
     {"id":9,"name":"\\u4e2d\\u4fe1\\u94f6\\u884c","status":1,"logo":"zhongxin","home":"http:\\/\\/bank.ecitic.com\\/","alias":"CCCB","sort":16},
     {"id":10,"name":"\\u6d66\\u53d1\\u94f6\\u884c","status":1,"logo":"pufa","home":"http:\\/\\/www.bankcomm.com","alias":"SPDB","sort":17},
     {"id":11,"name":"\\u5e7f\\u4e1c\\u53d1\\u5c55\\u94f6\\u884c","status":1,"logo":"guangfa","home":"http:\\/\\/www.cgbchina.com.cn","alias":"GDB","sort":13},
     {"id":12,"name":"\\u94f6\\u8054\\u5728\\u7ebf\\u652f\\u4ed8","status":1,"logo":"yinlian","home":"","alias":"CUP","sort":0},
     {"id":13,"name":"\\u534e\\u590f\\u94f6\\u884c","status":1,"logo":"minsheng","home":"http:\\/\\/www.hxb.com.cn\\/","alias":"CMBC","sort":0},
     {"id":14,"name":"\\u6613\\u5b9d\\u652f\\u4ed8","status":1,"logo":"huaxia","home":"http:\\/\\/www.yeepay.com","alias":"HXB","sort":0},
     {"id":15,"name":"\\u73af\\u8fc5\\u652f\\u4ed8","status":1,"logo":"pingan","home":"http:\\/\\/www.ips.com.cn","alias":"SDB","sort":0},
     {"id":16,"name":"\\u82b1\\u65d7\\u652f\\u4ed8","status":1,"logo":"huaqi","home":"http:\\/\\/www.010sms.com\\/","alias":"CTB","sort":0},
     {"id":17,"name":"\\u4e2d\\u56fd\\u5149\\u5927\\u94f6\\u884c","status":1,"logo":"guangda","home":"http:\\/\\/www.cebbank.com","alias":"CEB","sort":10},
     {"id":18,"name":"\\u4e2d\\u56fd\\u90ae\\u653f\\u94f6\\u884c","status":1,"logo":"youzheng","home":"http:\\/\\/www.psbc.com","alias":"PSBC","sort":11}]';
     $banks = json_decode($json);
     foreach ($banks as $bank) {
         DB::insert('insert into banks (name, status, logo, home_page, alias, sort) values (?, ?, ?, ?, ?,?)', [$bank->name, $bank->status, $bank->logo, $bank->home, $bank->alias, $bank->sort]);
     }
 }
 public function getInsertColumns()
 {
     return ['tableName' => 'users', 'validate' => $this->getValidatePost(), 'insert' => function ($table, $post) {
         $post['password'] = Auth::instance()->hash($post['password']);
         return DB::insert($table, array_keys($post))->values(array_values($post))->execute();
     }, 'columns' => self::getCommonColumns()];
 }
function updateMessageSettings($messages)
{
    if (!isset($messages['enabled'])) {
        $messages['enabled'] = 0;
    }
    if (isset($messages['triggers.severities'])) {
        $messages['triggers.severities'] = serialize($messages['triggers.severities']);
    }
    $dbProfiles = DBselect('SELECT p.profileid,p.idx,p.source,p.value_str' . ' FROM profiles p' . ' WHERE p.userid=' . CWebUser::$data['userid'] . ' AND ' . dbConditionString('p.idx', array('web.messages')));
    while ($profile = DBfetch($dbProfiles)) {
        $profile['value'] = $profile['value_str'];
        $dbMessages[$profile['source']] = $profile;
    }
    $inserts = array();
    $updates = array();
    foreach ($messages as $key => $value) {
        $values = array('userid' => CWebUser::$data['userid'], 'idx' => 'web.messages', 'source' => $key, 'value_str' => $value, 'type' => PROFILE_TYPE_STR);
        if (!isset($dbMessages[$key])) {
            $inserts[] = $values;
        } elseif ($dbMessages[$key]['value'] != $value) {
            $updates[] = array('values' => $values, 'where' => array('profileid' => $dbMessages[$key]['profileid']));
        }
    }
    try {
        DB::insert('profiles', $inserts);
        DB::update('profiles', $updates);
    } catch (APIException $e) {
        error($e->getMessage());
    }
    return $messages;
}
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     DB::table('roles')->insert(['name' => 'admin', 'display_name' => 'Admin', 'description' => 'Admin can manage users,articles,comments']);
     DB::table('roles')->insert(['name' => 'author', 'display_name' => 'Author', 'description' => 'Author can create and update articles']);
     DB::table('roles')->insert(['name' => 'user', 'display_name' => 'User', 'description' => 'User can make comments']);
     DB::insert('insert into role_user (user_id,role_id) values(?,?)', [1, 1]);
 }
Exemple #19
0
 protected function _update()
 {
     if (empty($this->_changed)) {
         return $this;
     }
     if ($this->_read_only) {
         return $this;
     }
     $vr = $this->_version_coloumn_reason;
     $old_item = ORM::factory($this->_object_name, $this->pk());
     $data = $old_item->as_array();
     $data[$vr] = $this->{$vr};
     $data[$this->_version_of] = $data[$this->_primary_key];
     unset($data[$this->_primary_key]);
     $result = DB::insert($this->_version_table_name)->columns(array_keys($data))->values(array_values($data))->execute($this->_db);
     if ($result) {
         if ($this->empty_pk()) {
             // $result is array(insert_id, total_rows)
             $this->_object[$this->_primary_key] = $result[0];
         }
     } else {
         throw "Error saving";
     }
     unset($data[$this->_version_coloumn_reason]);
     $v = $this->_version_coloumn_name;
     $this->{$v} += 1;
     if (is_array($this->_created_column)) {
         // Fill the created column
         $column = $this->_created_column['column'];
         $format = $this->_created_column['format'];
         $this->{$column} = $this->_object[$column] = $format === TRUE ? time() : date($format);
     }
     parent::_update();
 }
Exemple #20
0
 function insert($arr, $id)
 {
     global $_G;
     if (!$arr) {
         return false;
     }
     $arr['nick'] = $arr['nick'] ? trim($arr['nick']) : '';
     $arr['sid'] = $arr['sid'] ? trim($arr['sid']) : '';
     $arr['title'] = $arr['title'] ? trim($arr['title']) : '';
     $arr['desc'] = $arr['desc'] ? trim($arr['desc']) : '';
     $arr['pic_path'] = $arr['pic_path'] ? trim($arr['pic_path']) : '';
     $arr['picurl'] = $arr['picurl'] ? trim($arr['picurl']) : '';
     $arr['banner'] = $arr['banner'] ? trim($arr['banner']) : '';
     $arr['url'] = $arr['url'] ? trim($arr['url']) : '';
     $arr['start_time'] = dmktime($arr['start_time']);
     $arr['end_time'] = dmktime($arr['end_time']);
     $arr['zk'] = floatval($arr['zk']);
     $arr['cate'] = intval($arr['cate']);
     $arr['shop_type'] = intval($arr['shop_type']);
     $arr['hide'] = intval($arr['hide']);
     $arr['sort'] = intval($arr['sort']);
     if ($id > 0) {
         $id = DB::update('shop', $arr, 'id=' . $id);
         api_post(array('a' => 'update', 'table' => 'shop', 'data' => $arr, 'pre_key' => 'sid', 'id' => $arr['sid'], 'cache' => 'channels,all_channel'));
     } else {
         $arr['dateline'] = TIMESTAMP;
         $id = DB::insert('shop', $arr, 1);
         if ($id > 0) {
             api_post(array('a' => 'insert', 'table' => 'shop', 'data' => $arr, 'cache' => 'shop,shop_type', 'id' => $id));
         }
     }
     return $id;
 }
Exemple #21
0
 public function insert_by_uid($uid, $appids, $isall = 0)
 {
     if (!$appids) {
         return false;
     }
     if (!is_array($appids)) {
         $appids = array($appids);
     }
     //删除原来的
     $oids = array();
     $delids = array();
     $insertids = array();
     $oarr = DB::fetch_all("select * from " . DB::table('app_user') . " where uid='{$uid}'");
     foreach ($oarr as $value) {
         $oids[] = $value['appid'];
         if (!in_array($value['appid'], $appids)) {
             $delids[] = $value['id'];
         }
     }
     if ($isall && $delids) {
         self::delete($delids);
     }
     foreach ($appids as $appid) {
         if (!in_array($appid, $oids)) {
             DB::insert('app_user', array('uid' => $uid, 'appid' => $appid, 'dateline' => TIMESTAMP, 'num' => 1));
         }
     }
     return true;
 }
Exemple #22
0
 /**
  * Insert server
  *
  * @access	public
  * @param	array	$params
  *      client_id: AKA. API key
  *      client_secret: AKA. API secret
  *      redirect_uri: AKA. Callback URI
  *      scope: May be create, read, update or delete. so on so for
  *      secret_type: Secret signature encrypt type. e.g
  *      ssh_key: SSH public keys
  *      app_name: Application Name
  *      app_desc: Application Description, When users authenticate via your app, this is what they'll see.
  *      app_profile: Application Profile: Web Server Application, Native Application, Browser Application, Autonomous clients
  *      user_id: Ref# from users table
  *      user_level: diferent client levels have different max request times
  *      enabled: 0: waiting for system administrator audit; 1: acceptable; 2: ban
  *      created: create datetime
  *      modified: modified datetime
  *
  * @return	mix     array(insert_id, affect_rows) or validate object
  */
 public function append(array $params, $prefix = 'OAL_')
 {
     $params['client_id'] = $prefix . strtoupper(uniqid());
     $valid = Validate::factory($params)->filter(TRUE, 'trim')->rule('client_secret', 'not_empty')->rule('redirect_uri', 'not_empty')->rule('app_name', 'not_empty');
     $rules = array_intersect_key(array('client_id' => array('max_length' => array(128)), 'client_secret' => array('max_length' => array(128)), 'redirect_uri' => array('max_length' => array(512)), 'scope' => array('max_length' => array(256)), 'secret_type' => array('in_array' => array(array('plaintext', 'md5', 'rsa-sha1', 'hmac-sha1'))), 'ssh_key' => array('max_length' => array(512)), 'app_name' => array('max_length' => array(128)), 'app_desc' => array('max_length' => array(65535)), 'app_profile' => array('in_array' => array(array('webserver', 'native', 'useragent', 'autonomous'))), 'app_purpose' => array('max_length' => array(512)), 'user_level' => array('range' => array(0, 255)), 'enabled' => array('range' => array(0, 255)), 'modified' => array('range' => array(0, 2147483647))), $params);
     foreach ($rules as $field => $rule) {
         foreach ($rule as $r => $p) {
             $valid->rule($field, $r, $p);
         }
     }
     if ($valid->check()) {
         $valid = $valid->as_array();
         if ($this->unique_client($valid['redirect_uri'], $params['user_id'])) {
             return $valid->error('redirect_uri', 'not unique');
         }
         foreach ($valid as $key => $val) {
             if ($val === '') {
                 $valid[$key] = NULL;
             }
         }
         $valid['user_id'] = $params['user_id'];
         $valid['created'] = $_SERVER['REQUEST_TIME'];
         $valid['client_secret'] = sha1($params['client_secret']);
         $query = DB::insert('t_oauth_servers', array_keys($valid))->values(array_values($valid))->execute($this->_db);
         $valid['server_id'] = $query[0];
         $valid['affected_rows'] = $query[1];
         $valid += $params;
     }
     // Validation data, or collection of the errors
     return $valid;
 }
Exemple #23
0
 /**
  * Insert audit
  *
  * @access	public
  * @param	array	$params
  * @return	mix     array(insert_id, affect_rows) or validate object
  */
 public function append(array $params)
 {
     $valid = Validate::factory($params)->rule('created', 'not_empty');
     $rules = array_intersect_key(array('created' => array('range' => array(0, 2147483647)), 'nonce' => array('max_length' => array(64)), 'secret_type' => array('max_length' => array(32))), $params);
     foreach ($rules as $field => $rule) {
         foreach ($rule as $r => $p) {
             $valid->rule($field, $r, $p);
         }
     }
     if ($valid->check()) {
         $valid = $valid->as_array();
         foreach ($valid as $key => $val) {
             if ($val === '') {
                 $valid[$key] = NULL;
             }
         }
         $valid['company_id'] = (int) $params['company_id'];
         $valid['insert_by'] = OALite::$user['uid'];
         $valid['insert_time'] = $_SERVER['REQUEST_TIME'];
         return DB::insert('t_oauth_audits', array_keys($valid))->values(array_values($valid))->execute($this->_db);
     } else {
         // Validation failed, collect the errors
         return $valid;
     }
 }
 public function insert($uid, $data)
 {
     if (empty($uid) || empty($data)) {
         return false;
     }
     DB::insert($this->_table, array('uid' => intval($uid), 'data' => serialize($data)));
 }
Exemple #25
0
 /**
  * update account fields
  *
  * @param integer $account_id
  * @param array $data_fields
  * @return boolean
  */
 public function updateAccountFields($account_id = '', array $data_fields = array())
 {
     if (!is_numeric($account_id)) {
         return false;
     }
     // delete not exists fields.
     $current_af = static::getData($account_id);
     if ($current_af->count() > 0) {
         foreach ($current_af as $af) {
             if (!isset($data_fields[$af->field_name])) {
                 \DB::delete(static::$_table_name)->where('account_id', $account_id)->where('field_name', $af->field_name)->execute();
             }
         }
     }
     unset($af, $current_af);
     // update or insert fields.
     if (is_array($data_fields) && !empty($data_fields)) {
         foreach ($data_fields as $field_name => $field_value) {
             $result = \DB::select()->from(static::$_table_name)->where('account_id', $account_id)->where('field_name', $field_name)->execute();
             if (count($result) <= 0) {
                 // use insert
                 \DB::insert(static::$_table_name)->set(['account_id' => $account_id, 'field_name' => $field_name, 'field_value' => $field_value])->execute();
             } else {
                 // use update
                 \DB::update(static::$_table_name)->value('field_value', $field_value)->where('account_id', '=', $account_id)->where('field_name', $field_name)->execute();
             }
             unset($result);
         }
         unset($field_name, $field_value);
     }
     return true;
 }
Exemple #26
0
 public function __construct($table, $id = "new")
 {
     $this->table = $table;
     if ($id === "new") {
         $this->id = DB::insert("INTO {$table}('id') VALUES('')");
     }
 }
 public function insert()
 {
     $db = new DB();
     $data = $this->loadData();
     $this->id = $db->insert($data, $this->tableName);
     return true;
 }
Exemple #28
0
 public static function getManyToManyUpdate($arguments)
 {
     $through_table = $own_id = $foreign_id = $post_name = [];
     if (is_array($arguments)) {
         foreach ($arguments as $arg) {
             $through_table[] = $arg[0];
             $own_id[] = $arg[1];
             $foreign_id[] = $arg[2];
             $post_name[] = $arg[3];
         }
     } elseif (func_num_args() == 4) {
         $through_table = [func_get_arg(0)];
         $own_id = [func_get_arg(1)];
         $foreign_id = [func_get_arg(2)];
         $post_name = [func_get_arg(3)];
     }
     return function ($table, $post, $primaryColumn, $primary) use($through_table, $own_id, $foreign_id, $post_name) {
         /**
          * Many-to-many update first
          */
         foreach ($through_table as $index => $ttable) {
             DB::delete($ttable)->where($own_id[$index], '=', $primary)->execute();
             if (!empty($post[$post_name[$index]]) && $primary != 0) {
                 foreach ($post[$post_name[$index]] as $id) {
                     DB::insert($ttable)->values([$own_id[$index] => $primary, $foreign_id[$index] => $id])->execute();
                 }
                 unset($post[$post_name[$index]]);
             }
         }
         /**
          * Regular update
          */
         DB::update($table)->set($post)->where($primaryColumn, '=', $primary)->execute();
     };
 }
 function on_submit()
 {
     $user_name = AZLib::getParam('user_name');
     $content = AZLib::getParam('content');
     $active = (int) Url::get('active');
     $expire = (int) Url::get('expire', 7);
     $id = (int) Url::get('id');
     $cmd = Url::get('cmd');
     $sql = "SELECT id FROM user WHERE user_name='{$user_name}'";
     $row = DB::fetch($sql);
     $user_id = (int) $row["id"];
     if (!$user_id) {
         $this->setFormError('user_name', 'Không tồn tại thành viên này!');
     } elseif (!$user_name || !$content) {
         $this->setFormError('content', 'Dữ liệu không hợp lệ!');
     } else {
         if ($cmd == "add") {
             $item_array = array('content' => $content, 'user_name' => $user_name, 'user_id' => $user_id, 'admin_add' => User::user_name(), 'active' => $active, 'time_add' => TIME_NOW, 'expire_date' => TIME_NOW + 86400 * $expire);
             DB::insert('admin_notice_user', $item_array);
         } elseif ($cmd == "edit" && $id) {
             $item_array = array('content' => $content, 'user_name' => $user_name, 'user_id' => $user_id, 'admin_edit' => User::user_name(), 'active' => $active, 'time_edit' => TIME_NOW, 'expire_date' => TIME_NOW + 86400 * $expire);
             DB::update_id('admin_notice_user', $item_array, $id);
         }
         User::getAdminNoticeUser($user_id, 0, 1);
         Url::redirect_current(array('act'));
     }
 }
Exemple #30
0
 function updateTT()
 {
     if (!User::is_login() || !User::have_permit(ADMIN_AD_ITEM)) {
         echo 'not_perm';
         exit;
     }
     $id = (int) Url::get('ad_id');
     $type = (int) Url::get('type');
     $adItem = DB::select('ad_item', " status > -1 AND id = " . $id);
     // Cập nhật trạng thái thanh toán cho ad_item không bị xóa
     if ($adItem) {
         DB::update('ad_item', array('isPay' => 1), " id = " . $id);
         $arrInsert = array('type' => $type, 'user_id' => $adItem['user_id'], 'user_name' => $adItem['user_name'], 'admin_id' => User::id(), 'admin_name' => User::user_name(), 'cpc_id' => $adItem['id'], 'created' => TIME_NOW, 'click' => $adItem['click'], 'price' => $adItem['click'] * $adItem['per_price'], 'ad_type' => $adItem['ad_type'], 'link' => $adItem['link']);
         DB::insert('cpc_log', $arrInsert);
         if ($adItem['payType'] == 3) {
             // Cập nhật số lượng tiền trả sau đã dùng
             $money_used = $adItem['click'] * $adItem['per_price'] / 1000;
             // Trừ money_used của thành viên, tăng khả năng trả sau của khách hàng
             DB::query("UPDATE user SET money_used = money_used - (" . $money_used . ") WHERE id=" . $adItem['user_id']);
             // Cập nhật số tiền có thể trả sau vào cache thành viên
             User::getUser($adItem['user_id'], 0, 1);
             // Cập nhật trạng thái đã thanh toán cho bản ghi log trong bảng payment_premium
             DB::query("UPDATE payment_premium SET status = 1,user_m='" . User::user_name() . "',time_m=" . TIME_NOW . " WHERE log_id={$id} AND type=4");
         }
         echo 'success';
     } else {
         echo 'not_ad';
     }
     exit;
 }