示例#1
0
 public function postLunbo()
 {
     $options = $this->request()->only(['lb_image1', 'lb_url1', 'lb_title1', 'lb_image2', 'lb_url2', 'lb_title2', 'lb_image3', 'lb_url3', 'lb_title3']);
     try {
         transaction();
         foreach ($options as $key => $option) {
             Option::where('key', $key)->update(['value' => $option]);
         }
         commit();
         return $this->success('保存成功');
     } catch (\Exception $exception) {
         rollback();
     }
     return $this->error('修改失败,请稍后再试');
 }
示例#2
0
 /** Commits a transaction. */
 public function commit()
 {
     if ($this->rollBackOnly == true) {
         rollback();
         return;
     }
     --$this->count;
     if ($this->count == 0) {
         try {
             $this->doCommit();
         } finally {
             sem_release($this->semId);
         }
     }
 }
示例#3
0
 public function incluirFuncionario($id, $credencial)
 {
     // $objDatos = new clsDatos();
     $this->objDatos = new clsDatos();
     $this->objDatos->conectar();
     try {
         $sql = "INSERT INTO Funcionario(credencial_fun,cod_per,status_fun) VALUES ('{$credencial}','{$id}','activo')";
         $this->objDatos->ejecutar($sql);
     } catch (Exception $e) {
         rollback();
         // transaction rolls back
         echo "<script>alert('Error al Insertar')</script>";
         exit;
     }
     $this->objDatos->desconectar();
     return;
 }
function UpdatePlanetBatimentQueueList($planetid)
{
    $RetValue = false;
    $now = time();
    begin_transaction();
    $CurrentPlanet = doquery("SELECT * FROM {{table}} WHERE `id` = '" . $planetid . "' FOR UPDATE", 'planets', true);
    if (!$CurrentPlanet || $CurrentPlanet['b_building'] == 0 || $CurrentPlanet['b_building'] > $now) {
        rollback();
        return false;
    }
    $CurrentUser = doquery("SELECT * FROM {{table}} WHERE `id` = '" . $CurrentPlanet['id_owner'] . "' LOCK IN SHARE MODE", 'users', true);
    if (!$CurrentUser) {
        return false;
    }
    PlanetResourceUpdate($CurrentUser, $CurrentPlanet, $CurrentPlanet['b_building'], false);
    CheckPlanetBuildingQueue($CurrentPlanet, $CurrentUser);
    commit();
}
示例#5
0
 public function check()
 {
     $this->begin('index.php?app=seller&ctl=admin_brand&act=index');
     if (!$_POST) {
         $this->end(false, '非法请求');
     }
     extract($_POST);
     $mdl_brand = $this->app->model('brand');
     $db = vmc::database();
     $db->beginTransaction();
     if ($status == 1) {
         $mdl_b2c_brand = app::get('b2c')->model('brand');
         if (!($brand_id = $mdl_b2c_brand->insert($brand))) {
             $db->rollback();
         }
     }
     $data = compact('id', 'brand_id', 'status', 'why');
     if (!$mdl_brand->save($data)) {
         $db - rollback();
         $this->end(false, '审核失败');
     }
     $db->commit();
     $this->end(true, '审核成功');
 }
示例#6
0
    }
    $sql .= ' WHERE dav_name = :src_name';
    $params[':src_name'] = $src_name;
    $qry = new AwlQuery($sql, $params);
    if (!$qry->Exec('move')) {
        rollback(500);
    }
    $qry = new AwlQuery('SELECT write_sync_change( :src_collection, 404, :src_name );', array(':src_name' => $src_name, ':src_collection' => $src_collection));
    if (!$qry->Exec('move')) {
        rollback(500);
    }
    if (function_exists('log_caldav_action')) {
        log_caldav_action('DELETE', $src->GetProperty('uid'), $src_user_no, $src_collection, $src_name);
    }
    $qry = new AwlQuery('SELECT write_sync_change( :dst_collection, :sync_type, :dst_name );', array(':dst_name' => $dst_name, ':dst_collection' => $dst_collection, ':sync_type' => $dest->Exists() ? 200 : 201));
    if (!$qry->Exec('move')) {
        rollback(500);
    }
    if (function_exists('log_caldav_action')) {
        log_caldav_action($dest->Exists() ? 'UPDATE' : 'INSERT', $src->GetProperty('uid'), $dst_user_no, $dst_collection, $dst_name);
    }
}
$qry = new AwlQuery('COMMIT');
if (!$qry->Exec('move')) {
    rollback(500);
}
// We need to delete from the cache *after* we commit the transaction :-)
foreach ($cachekeys as $cache_ns) {
    $cache->delete($cache_ns, null);
}
$request->DoResponse(200);
示例#7
0
function insert_sql_data( $db_conn, $p_campaigns, $p_headers, $p_details )
// insert the header and detail data into the file
// with appropriate safeguards to ensure full 
// completion or rollback of the transaction.
{
GLOBAL $msg_log;

	$success = TRUE;
// Wrap all this in a transaction
// First, turn off autocommit
	$qry = "set autocommit=0";
//pre_echo( $qry );
	$success = mysql_query( $qry, $db_conn );

// Second, take care of all ALTER TABLE queries.  Due to a (documented)
// glitch in MySQL, these commands force a transaction to commit, 
// which sucks.

	if ($success) 
	{ // Create the temp_header table
		$qry = "CREATE TEMPORARY TABLE temp_header LIKE contract_header";
//pre_echo( $qry );
		$success = mysql_query( $qry, $db_conn );
		if (!$success) 
		{
			message_log_append( $msg_log, mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	}

	if ($success) 
	{ // Create the temp_detail table
		$qry = "CREATE TEMPORARY TABLE temp_detail LIKE contract_detail";
//pre_echo( $qry );
		$success = mysql_query( $qry, $db_conn );
		if (!$success)
		{
			message_log_append( $msg_log, mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	}

	if ($success) 
	{ // Delete the Seq field from table temp_header
		$qry = "ALTER TABLE temp_header DROP COLUMN Seq";
//pre_echo( $qry );
		$success = mysql_query( $qry, $db_conn );
		if (!$success)
		{
			message_log_append( $msg_log, mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	}

    if ($success) 
	{ // Delete the Line column from table temp_detail
		$qry = "ALTER TABLE temp_detail DROP COLUMN Line";
//pre_echo( $qry );
		$success = mysql_query( $qry, $db_conn );
		if (!$success)
		{
			message_log_append( $msg_log, mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	}

// loop through the campaigns, headers, and details to insert the
// data into the SQL database.  Keep solid track of all error
// results so that we can ROLLBACK on any error.
	if ($success) 
	{
//echo "<pre>";
//var_dump( $p_campaigns );  echo "</pre><br>";
		$success = begin( $db_conn );
		if (!$success)
		{
			message_log_append( $msg_log, "Error in START TRANSACTION: " . mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	}

// do the work here, and keep track of $success
// If we need to create a new agency record, do that here.
	$new_agency = FALSE;
	if ($success && is_null( $p_campaigns[0][ 'Agency Record' ])) 
	{
		$agent_name = $p_campaigns[0][ 'Agency Name' ];
		$rate = DEFAULT_AGENCY_RATE / 10;
		if ($success = agency_insert( $db_conn, $agent_name, $rate, $aindex )) 
		{
			$p_campaigns[0][ 'Agency Record' ] = agency_record( $agent_name, OPERATOR_NAME );
			$success = !is_null( $p_campaigns[0][ 'Agency Record' ]);
		} // if agency_insert
		if ($success) 
		{
			$new_agency = TRUE;
			message_log_append( $msg_log, "Agency created: " .
			"Seq = $aindex, Name = '$agent_name'", MSG_LOG_WARNING );
		} 
		else 
		{
			message_log_append( $msg_log, "Error while creating " . "Agency '$agent_name': " . mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	} // if null agency record

// If we need to create a new customer record, do that here.

	$new_customer = FALSE;
	if ($success && is_null( $p_campaigns[0][ 'Customer Record' ])) 
	{
		$cust_name = $p_campaigns[0][ 'Customer Name' ];
		$rate = DEFAULT_CUST_DISCOUNT;
		if ($success = customer_insert( $db_conn, $cust_name, $rate, $cindex )) 
		{
			$p_campaigns[0][ 'Customer Record' ] = cust_record( $cust_name, OPERATOR_NAME );
			$success = !is_null( $p_campaigns[0][ 'Customer Record' ]);
		} // if customer_insert
		if ($success) 
		{
			$new_customer = TRUE;
			message_log_append( $msg_log, "Customer created: " . "Seq = $cindex, Name = '$cust_name'", MSG_LOG_WARNING );
		} 
		else 
		{
			message_log_append( $msg_log, "Error while creating " . "Customer '$cust_name' " . mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	} // if null customer record

	if ($success) 
	{
// build the list of header fields, in order with 'quote required' flag
//  [n][0] is field name, [n][1] is boolean T=quote required, F=not
		$hdr_flds = build_header_field_array();
// A SQL INSERT statement lead-in
		$hdr_sql  = "INSERT INTO temp_header ( ";
		$hdr_sql .= fld_list( $hdr_flds ) . ") VALUES\n";

// build the list of detail fields, in order with 'quote required' flag
//  [n][0] is field name, [n][1] is boolean T=quote required, F=not

		$det_flds = build_detail_field_array();

// A SQL INSERT statement lead-in
		$det_sql  = "INSERT INTO temp_detail ( ";
		$det_sql .= fld_list( $det_flds ) . ") VALUES ";

// Here we go.  We'll loop through each contract header record,
// and its accompanying detail records.

		$n_inserted = 0;

		while ($success && (list( $key ) = each( $p_headers ))) 
		{
		    if (count( $p_details[ $key ] ) > 0) 
			{
//	If we created a new agency or customer above, update 
//	the respective header fields.
				if ($new_customer) 
				{
					$p_headers[ $key ][ 'CIndex' ] = $cindex;
					$p_headers[ $key ][ 'Discount' ] = $p_campaigns[0][ 'Customer Record' ][ 'Discount' ];
				}
				if ($new_agency) 
				{
					$p_headers[ $key ][ 'AIndex' ] = $aindex;
					$p_headers[ $key ][ 'AgencyComm' ] = $p_campaigns[0][ 'Agency Record' ][ 'Rate' ];
				}
				$row = data_values( $hdr_flds, $p_headers[ $key ] );
				$sql_header  = $hdr_sql;	// INSERT INTO ... VALUES
				$sql_header .= "(" . $row . ");";

				$rows = "";
				foreach ($p_details[ $key ] as $line)
				{
					$rows .= ",\n( " . data_values( $det_flds, $line ) . " )";
				}
				$rows = substr( $rows, 1 );	// remove comma-newline
				$sql_detail  = $det_sql;	// INSERT INTO ... VALUES
				$sql_detail .= $rows;

				if ($success = do_insert( $db_conn, $sql_header, $sql_detail ))
				{
					$n_inserted++;
				}
			} // if detail count > 0
		} // while success and each key
	} // if success

	if ($success) 
	{
		$success = commit( $db_conn );
		if ($success)
		{
			message_log_append( $msg_log, "$n_inserted contract" . ($n_inserted == 1 ? '' : 's') . " imported" );
		}
		else 
		{
			message_log_append( $msg_log, "Error in COMMIT TRANSACTION: " . mysql_error( $db_conn ), MSG_LOG_ERROR );
			if (!rollback( $db_conn ))
			{
				message_log_append( $msg_log, "Error in ROLLBACK TRANSACTION: " . mysql_error( $db_conn ), MSG_LOG_ERROR );
			}
		}
	} 
	else 
	{
		if (!rollback( $db_conn ))
		{
			message_log_append( $msg_log, "Error in ROLLBACK TRANSACTION: " . mysql_error( $db_conn ), MSG_LOG_ERROR );
		}
	} // if success
	return( $success );
} // insert_sql_data
示例#8
0
 public function rollback()
 {
     return rollback($this->conn);
 }
示例#9
0
 public function postAdd(Register $register)
 {
     //验证表单
     $this->validate($this->request(), ['mobile' => 'required|digits:11', 'birthday' => 'required|date', 'sex' => 'required|in:' . array_keys_impload(UserEnum::$sexForm), 'password' => 'required|min:5|max:20', 'password_confirm' => 'required|required_with:password|same:password', 'marital_status' => 'in:' . array_keys_impload(UserEnum::$maritalForm), 'height' => 'digits:3|between:130,210', 'education' => 'in:' . array_keys_impload(UserEnum::$educationForm), 'salary' => 'in:' . array_keys_impload(UserEnum::$salaryForm), 'user_name' => 'required|min:2|max:15|unique:users', 'email' => 'required|email|unique:users']);
     $form = $this->request()->only(['user_name', 'email', 'mobile', 'birthday', 'password', 'marital_status', 'height', 'education', 'salary', 'province', 'city', 'area']);
     try {
         transaction();
         $user = User::create($form);
         $register->delete();
         commit();
         return $this->success('添加成功', $user);
     } catch (\Exception $exp) {
         rollback();
         return $this->error('抱歉,添加失败');
     }
 }
示例#10
0
     }
     $result = dump_database($next_ver);
     if ($result === false) {
         echo implode(',', $err->last_message());
     } else {
         echo 'OK';
     }
     break;
 case 'rollback':
     include_once ROOT_PATH . 'includes/cls_json.php';
     $json = new JSON();
     $next_ver = isset($_REQUEST['next_ver']) ? $_REQUEST['next_ver'] : '';
     if ($next_ver === '') {
         die('EMPTY');
     }
     $result = rollback($next_ver);
     if ($result === false) {
         echo implode(',', $err->last_message());
     } else {
         echo 'OK';
     }
     break;
     /* 升级文件 */
 /* 升级文件 */
 case 'update_files':
     include_once ROOT_PATH . 'includes/cls_json.php';
     $json = new JSON();
     $next_ver = isset($_REQUEST['next_ver']) ? $_REQUEST['next_ver'] : '';
     if ($next_ver === '') {
         die('EMPTY');
     }
示例#11
0
// 写超级管理基本授权
$sql = "SELECT * FROM auth_node WHERE node = 'account.authorize.put'";
$sth = $pdo->query($sql);
$sth->execute();
$auth_node = $sth->fetch(PDO::FETCH_ASSOC);
if (!$auth_node) {
    rollback($pdo);
    return send_exit_single('user role authorize failed (fetch auth node).');
}
$sql = "INSERT INTO authorize(flag, company_id, auth_role_id, auth_node_id)VALUE(1, :company_id, :auth_role_id, :auth_node_id)";
$prepared = $pdo->prepare($sql);
$prepared->bindParam(':company_id', $company_id);
$prepared->bindParam(':auth_role_id', $auth_role_id);
$prepared->bindParam(':auth_node_id', $auth_node['id']);
if (!$prepared->execute()) {
    rollback($pdo);
    return send_exit_single('user role authorize failed (authorize).');
}
// 创建session表
$pdo->exec("CREATE TABLE IF NOT EXISTS `session` (\n  `session_id` varchar(255) NOT NULL,\n  `session_expire` int(11) NOT NULL,\n  `session_data` blob,\n  UNIQUE KEY `session_id` (`session_id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
// 写应用表
$sql = "INSERT INTO app(alias, requirements)VALUES(:alias, :requirements)";
$prepared = $pdo->prepare($sql);
foreach ($apps as $alias => $app_config) {
    $requirements = $app_config['requirements'];
    $prepared->bindParam(':alias', $alias);
    $prepared->bindParam(':requirements', $requirements);
    $prepared->execute();
}
display_loading('initialize company and super-user', 5);
file_put_contents(ENTRY_PATH . '/Data/install.lock', time());
示例#12
0
                            $response .= $res . "|||";
                            if ($datato == 'citas') {
                                $amot = 'Pac: ' . $_POST["PACIENTE_CIT"] . ' - Esp: ' . $_POST["BAREMO_CIT"] . ' - Med: ' . $_POST["PROVEEDOR_CIT"];
                            }
                            audit($datato, 'I', $res, $amot);
                        }
                    } elseif (isset($_POST[$_GET["saveidcampo" . $ix]])) {
                        $response .= $_POST[$_GET["saveidcampo" . $ix]] . "|||";
                    } elseif (isset($adds[$_GET["saveidcampo" . $ix]])) {
                        $response .= $adds[$_GET["saveidcampo" . $ix]] . "|||";
                    }
                }
            }
        }
    } else {
        $data = "<span style='color:green'><br>Ya existe este codigo<b/><br/>Ya sido cargado en el formulario</span>|||" . $_POST[$saveidcampo];
        rollback();
    }
    $txt = "agregados";
}
if ($data) {
    echo $data;
} else {
    if ($result) {
        echo "<b>Datos {$txt} con exito...</b>|||" . $response;
    } else {
        //putxt(mssql_get_last_message());
        echo "<span style='color:#999'>No se completo la operaci&oacute;n...</span>|||" . $response;
    }
}
commit();
示例#13
0
 function saveIndiceEstacional($oData)
 {
     begin();
     $sql = "SELECT * FROM indices_estacionales WHERE id_producto = " . $oData["id_producto"];
     $result = getRS($sql);
     if (!getNrosRows($result)) {
         $dur_periodo = $this->getDuracionPeriodo();
         $cant_dias_anio = date("z", mktime(0, 0, 0, 12, 31, date("Y"))) + 1;
         $periodo_x_anio = number_format($cant_dias_anio / $dur_periodo);
         for ($i = 0; $i < $periodo_x_anio; $i++) {
             if ($i + 1 == $oData["nro_estacion"]) {
                 $sql = "INSERT INTO indices_estacionales (id_producto, orden, valor) VALUES (" . $oData["id_producto"] . "," . ($i + 1) . ", " . $oData["indice_estacional"] . ")";
             } else {
                 $sql = "INSERT INTO indices_estacionales (id_producto, orden) VALUES (" . $oData["id_producto"] . "," . ($i + 1) . ")";
             }
             $rs = getRS($sql);
             if (!$rs) {
                 die('Error: ' . mysql_error());
                 rollback();
             } else {
                 commit();
             }
         }
     } else {
         $sql = "SELECT * FROM indices_estacionales WHERE id_producto = " . $oData["id_producto"] . " and orden = " . $oData["nro_estacion"];
         $result = getRS($sql);
         if (!getNrosRows($result)) {
             $sql = "INSERT INTO indices_estacionales (id_producto, orden, valor) VALUES (" . $oData["id_producto"] . "," . $oData["nro_estacion"] . ", " . $oData["indice_estacional"] . ")";
             $rs = getRS($sql);
             if (!$rs) {
                 die('Error: ' . mysql_error());
                 rollback();
             }
         } else {
             $sql = "UPDATE indices_estacionales SET valor = " . $oData["indice_estacional"] . " WHERE id_producto = " . $oData["id_producto"] . " AND orden = " . $oData["nro_estacion"];
             $rs = getRS($sql);
             if (!$rs) {
                 die('Error: ' . mysql_error());
                 rollback();
             }
         }
     }
 }
示例#14
0
 public function postRegister()
 {
     $this->validate($this->request(), array('realname' => 'required', 'mobile' => 'required|size:11|unique:users,mobile', 'sex' => 'required:in:' . array_keys_impload(\App\Enum\User::$sexLang), 'birthday' => 'required|date', 'marriage' => 'required|in:' . array_keys_impload(\App\Enum\User::$marriageLang), 'like' => 'exists:users,user_id'), array('realname.required' => '请填写真实姓名', 'mobile.required' => '请填写手机号', 'mobile.size' => '手机号格式不正确', 'mobile.unique' => '手机号已被注册', 'sex.required' => '请选择您的性别', 'sex.in' => '您填写的性别有误', 'birthday.required' => '请填写您的生日', 'birthday.date' => '您填写的生日格式不正确', 'marriage.required' => '您填写您的婚姻状态', 'marriage.in' => '婚姻状态不正确', 'like.exist' => '您报名的对象不存在'));
     $form = $this->request()->only('realname', 'mobile', 'sex', 'birthday', 'marriage');
     try {
         transaction();
         //创建用户
         $user = User::create($form);
         if ($this->request()->has('like')) {
             //创建喜欢的人
             $user->like()->create(array('like_user_id' => $this->request()->get('like')));
         }
         //创建用户信息
         $user->info()->create(array());
         //创建择偶条件
         $user->object()->create(array('sex' => $user->sex == \App\Enum\User::SEX_FEMALE ? \App\Enum\User::SEX_MALE : \App\Enum\User::SEX_FEMALE));
         commit();
         return $this->rest()->success($user, '报名成功,管理员审核通过后即可登录');
     } catch (\Exception $ex) {
         rollback();
         dd($ex->getMessage());
         return $this->rest()->error('抱歉,报名失败,请稍后再试');
     }
 }
 function update($p_array)
 {
     $this->load();
     // if name is empty return immediately
     if (trim(strlen($p_array['md_name'])) == 0) {
         return;
     }
     try {
         // Start transaction
         $this->cn->start();
         $sql = "update document_modele set md_name=\$1,md_type=\$2,md_affect=\$3 where md_id=\$4";
         $this->cn->exec_sql($sql, array($p_array['md_name'], $p_array['md_type'], $p_array['md_affect'], $this->md_id));
         if ($p_array['seq'] != 0) {
             $this->cn->alter_seq('seq_doc_type_' . $p_array['md_type'], $p_array['seq']);
         }
         // Save the file
         $new_name = tempnam($_ENV['TMP'], 'document_');
         if (strlen($_FILES['doc']['tmp_name']) != 0) {
             if (move_uploaded_file($_FILES['doc']['tmp_name'], $new_name)) {
                 // echo "Image saved";
                 $oid = $this->cn->lo_import($new_name);
                 if ($oid == false) {
                     echo_error('class_document_modele.php', __LINE__, "cannot upload document");
                     $this->cn->rollback();
                     return;
                 }
                 // Remove old document
                 $ret = $this->cn->exec_sql("select md_lob from document_modele where md_id=" . $this->md_id);
                 if (Database::num_row($ret) != 0) {
                     $r = Database::fetch_array($ret, 0);
                     $old_oid = $r['md_lob'];
                     if (strlen($old_oid) != 0) {
                         $this->cn->lo_unlink($old_oid);
                     }
                 }
                 // Load new document
                 $this->cn->exec_sql("update document_modele set md_lob=" . $oid . ", md_mimetype='" . $_FILES['doc']['type'] . "' ,md_filename='" . $_FILES['doc']['name'] . "' where md_id=" . $this->md_id);
                 $this->cn->commit();
             } else {
                 echo "<H1>Error</H1>";
                 $this->cn->rollback();
                 throw new Exception("Erreur" . __FILE__ . __LINE__);
             }
         }
     } catch (Exception $e) {
         rollback($this->cn);
         return;
     }
     $this->cn->commit();
 }
示例#16
0
/**
 * @post update
 */
function update_post_controller($id)
{
    __is_guest();
    if (!empty($_POST)) {
        if (checked_token($_POST['_token'])) {
            __session_start();
            $_SESSION['old'] = [];
            $_SESSION['errors'] = [];
            $rules = ['title' => FILTER_SANITIZE_STRING, 'content' => FILTER_SANITIZE_STRING, 'status' => ['filter' => FILTER_CALLBACK, 'options' => function ($s) {
                if (in_array($s, ['published', 'unpublished'])) {
                    return $s;
                } else {
                    return 'unpublished';
                }
            }], 'published_at' => ['filter' => FILTER_CALLBACK, 'options' => function ($checkbox) {
                if ($checkbox == 'yes') {
                    return new DateTime('now');
                }
            }]];
            $sanitize = filter_input_array(INPUT_POST, $rules);
            $id = (int) $id;
            // test if errors
            if (empty($_POST['title'])) {
                $_SESSION['errors']['title'] = 'title is required';
            }
            if (!empty($_SESSION['errors'])) {
                $_SESSION['old'] = $sanitize;
                redirect('post/create');
                // exit
            }
            if (!empty($_FILES['file']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                try {
                    $dateFile = upload($_FILES['file']);
                    beginTransaction();
                    update_post_model($id, $sanitize);
                    create_media_model(['filename' => $dateFile['filename'], 'post_id' => $id, 'size' => $dateFile['size']]);
                    commit();
                    setFlashMessage("success stored");
                    redirect('dashboard');
                } catch (Exception $e) {
                    if ($e instanceof RuntimeException) {
                        $_SESSION['old'] = $sanitize;
                        $_SESSION['errors']['upload'] = $e->getMessage();
                        redirect('post/create');
                    }
                    rollback();
                    $_SESSION['old'] = $sanitize;
                    $_SESSION['errors']['file'] = $e->getMessage();
                    redirect('post/create');
                }
            } else {
                try {
                    beginTransaction();
                    update_post_model($id, $sanitize);
                    $media_id = (int) $_POST['m_id'];
                    if (!empty($_POST['m_id']) && !empty($_POST['delete_filename'])) {
                        $media = find_model($media_id, 'medias');
                        $m = $media->fetch();
                        destroy_model($media_id, 'medias');
                    }
                    commit();
                    if (!empty($m)) {
                        unlink(getEnv('UPLOAD_DIRECTORY') . '/' . htmlentities($m['m_filename']));
                    }
                    setFlashMessage(trans('success_updated_post', $sanitize['title']));
                    redirect('dashboard');
                } catch (Exception $e) {
                    rollback();
                    $_SESSION['old'] = $sanitize;
                    $_SESSION['errors']['file'] = $e->getMessage();
                    redirect('post/create');
                }
                throw new RuntimeException('418');
            }
        }
    }
}
示例#17
0
		die ('No se encuentra la base de datos seleccionada : ' . mysql_error());
	}
	
	$lNumber = $_POST['leaseNum'];
	$sDate = $_POST['sDate'];
	$eDate = $_POST['eDate'];
	$duration = $_POST['duration'];
	$studentID = $_POST['student'];
	$placeNum = $_POST['room'];
	

	$contrato = "INSERT INTO Lease VALUES ('$lNumber', '$sDate', '$eDate', '$duration', '$studentID', '$placeNum')";
	begin(); // Empieza la transaccion
	$result = mysql_query($contrato);
	
	if(!$result) {
		
		rollback(); // Si hubo un error se le da rollback
		echo 'Hubo un error';
		exit;
	}
	
	else {
		commit(); //Si fue exitosa se lleva a cabo
		echo 'Operación realizada con éxito';
	}
	
	
	header("Location: confirmacion.php");
?>
示例#18
0
function exception_error_handler($errno, $errstr, $errfile, $errline)
{
    rollback();
}
示例#19
0
 function crearItemsDeCarga($id)
 {
     begin();
     if ($this->cargaExists($id)) {
         if (!$this->eliminarItemsDeCarga($id)) {
             rollback();
         }
     }
     $sql = "INSERT INTO cargas (id_reparto, id_producto, cantidad, fecha_update)\n                SELECT  t1.id_reparto, \n                        t4.id_producto,\n                        SUM(t3.cantidad_detalle_venta) cantidad,\n                        NOW()\n                FROM repartos t1\n                INNER JOIN ventas t2 ON t1.id_reparto=t2.id_reparto\n                INNER JOIN detalle_ventas t3 ON t2.id_venta=t3.id_venta\n                INNER JOIN productos t4 ON t3.id_producto=t4.id_producto\n                WHERE t1.id_reparto != 1 AND t1.id_reparto = {$id}\n                GROUP BY t4.id_producto\n                ORDER BY detalle_producto";
     if (!mysql_query($sql)) {
         die('Error: ' . mysql_error());
         rollback();
         return false;
     } else {
         commit();
         return true;
     }
 }
示例#20
0
 function index()
 {
     if ($this->method !== 'post') {
         $this->error('403', 'Forbidden');
         return;
     }
     copy(FCPATH . 'app/koken/recover.php', FCPATH . 'recover.php');
     function rollback($back)
     {
         foreach ($back as $b) {
             $f = FCPATH . $b;
             $dest = str_replace('.off', '', $f);
             if (is_dir($dest)) {
                 delete_files($dest, true, 1);
             } else {
                 if (file_exists($dest)) {
                     unlink($dest);
                 }
             }
             @rename($f, $dest);
         }
     }
     function fail($msg = 'Koken does not have the necessary permissions to perform the update automatically. Try setting the permissions on the entire Koken folder to 777, then try again.')
     {
         @unlink(FCPATH . 'recover.php');
         delete_files(FCPATH . 'storage/tmp', true);
         die(json_encode(array('error' => $msg)));
     }
     $get_core = $this->input->post('url');
     if ($get_core) {
         if (ENVIRONMENT === 'development') {
             $manifest = FCPATH . 'manifest.php';
             require $manifest;
             if (count($compatCheckFailures)) {
                 die(json_encode(array('requirements' => $compatCheckFailures)));
             }
             //hack
             sleep(2);
             // fail();
             unlink(FCPATH . 'recover.php');
             die(json_encode(array('migrations' => array('0001.php', '0001.php', '0001.php'))));
         }
         $old_mask = umask(0);
         $core = FCPATH . 'storage/tmp/core.zip';
         make_child_dir(dirname($core));
         if ($this->_download($get_core, $core)) {
             $this->load->library('unzip');
             $this->unzip->extract($core);
             @unlink($core);
             $manifest = FCPATH . 'storage/tmp/manifest.php';
             require $manifest;
             if (count($compatCheckFailures)) {
                 delete_files(FCPATH . 'storage/tmp', true);
                 unlink(FCPATH . 'recover.php');
                 die(json_encode(array('requirements' => $compatCheckFailures)));
             }
             $migrations_before = scandir($this->migrate_path);
             $moved = array();
             // updateFileList comes from manifest.php
             foreach ($updateFileList as $path) {
                 $fullPath = FCPATH . 'storage/tmp/' . $path;
                 $dest = FCPATH . $path;
                 $off = $dest . '.off';
                 if (!file_exists($fullPath)) {
                     rollback($moved);
                     umask($old_mask);
                     fail();
                 }
                 if (file_exists($dest)) {
                     if (file_exists($off)) {
                         delete_files($off, true, 1);
                     }
                     if (rename($dest, $off)) {
                         $moved[] = $path;
                     } else {
                         rollback($moved);
                         umask($old_mask);
                         fail();
                     }
                 }
                 if (!rename($fullPath, $dest)) {
                     rollback($moved);
                     umask($old_mask);
                     fail();
                 }
             }
             foreach ($moved as $m) {
                 $path = FCPATH . $m . '.off';
                 if (is_dir($path)) {
                     delete_files($path, true, 1);
                 } else {
                     if (file_exists($path)) {
                         unlink($path);
                     }
                 }
             }
             unlink(FCPATH . 'recover.php');
             @unlink(FCPATH . 'manifest.php');
             // Remove temporary update files
             delete_files(FCPATH . 'storage/tmp', true);
             if (is_really_callable('opcache_reset')) {
                 opcache_reset();
             }
             die(json_encode(array('migrations' => array_values(array_diff(scandir($this->migrate_path), $migrations_before)))));
         } else {
             umask($old_mask);
             @unlink($core);
             fail();
         }
     }
 }
示例#21
0
        // Update the parent record to reflect count and start, end times.
        if (!perform_query($query, $dbLink)) {
            rollback($dbLink);
            die("Error: Update failed.");
        }
        // Delete all the child records.
        // Create a set of SQL IN lists (e.g. "('seq1', 'seq2',...).  You
        // need a set because there can be limits of 255 IN list members.
        // print "Splitting lists into array of 255\n";
        $lists = array_chunk($message_data['child_seqs'], $max_sql_in_list_count);
        foreach ($lists as $list) {
            $in_list = create_sql_in_list($list);
            $query = "DELETE FROM " . DEFAULTLOGTABLE . " WHERE seq IN {$in_list}";
            // print "Processing in list\n";
            if (!perform_query($query, $dbLink)) {
                rollback($dbLink);
                die("Error: Delete failed.");
            }
        }
    }
}
commit($dbLink);
$dbsecs = get_microtime() - $db_time_start;
print "Debug: Log table modifications complete in {$dbsecs} seconds...\n";
//------------------------------------------------------------------------
// Gather and spit out some stats
//------------------------------------------------------------------------
$query = 'SELECT count(*) AS "count" from ' . DEFAULTLOGTABLE;
$result = perform_query($query, $dbLink);
$row = fetch_array($result);
$num_rows_after = $row['count'];
示例#22
0
 public function getSeedMaleAvatar()
 {
     $FILE = new \Illuminate\Filesystem\Filesystem();
     $files = $FILE->files('/Users/vicens/www/meigui/public/uploads/avatar');
     try {
         transaction();
         foreach ($files as $path) {
             $file = $FILE->name($path) . '.jpg';
             $user = User::where('sex', UserEnum::SEX_MALE)->whereNull('avatar')->first();
             if ($user && !$user->getOriginal('avatar')) {
                 $user->update(array('avatar' => $file));
             }
         }
         commit();
         return '添加成功';
     } catch (\Exception $e) {
         rollback();
         return $e->getMessage();
     }
 }
示例#23
0
{
    oci_commit($conn);
    echo $conn . " committed\n\n";
}
$conn = oci_connect('ndjsb', 'dmndjsb', '172.24.132.14/jsbdb', 'AL32UTF8');
var_dump($conn);
exit;
create_table($c1);
insert_data($c1);
// Insert a row using c1
insert_data($c2);
// Insert a row using c2
select_data($c1);
// Results of both inserts are returned
select_data($c2);
rollback($c1);
// Rollback using c1
select_data($c1);
// Both inserts have been rolled back
select_data($c2);
insert_data($c2);
// Insert a row using c2
commit($c2);
// Commit using c2
select_data($c1);
// Result of c2 insert is returned
delete_data($c1);
// Delete all rows in table using c1
select_data($c1);
// No rows returned
select_data($c2);
示例#24
0
 function save($oData)
 {
     if (!$oData["id_orden_compra"]) {
         begin();
         $detalle = array();
         $cabecera = array();
         $cabecera = explode("@@", $oData["cabecera"]);
         $detalle = explode("||", $oData["detalle"]);
         $sql = "INSERT INTO  ordenes_compra (id_proveedor, fecha_orden_compra, nro_orden_compra, generada)\r\n\t\t\t\t\tVALUES (" . $cabecera[0] . ", '" . dateToMySQL($cabecera[1]) . "', " . $cabecera[2] . ", 1)";
         if (!mysql_query($sql)) {
             die('Error: ' . mysql_error());
             rollback();
             return false;
         } else {
             $id = mysql_insert_id();
             foreach ($detalle as $detail) {
                 $values = explode("@@", $detail);
                 $sql = "INSERT INTO detalle_ordenes_compra (id_orden_compra, id_producto, cantidad_detalle_orden_compra) VALUES  (" . $id . ", " . $values[0] . ", " . $values[1] . ")";
                 if (!mysql_query($sql)) {
                     die('Error: ' . mysql_error());
                     rollback();
                     break;
                 }
             }
             if ($cabecera[2]) {
                 $nroVta = $cabecera[2] + 1;
             }
             $sql = "UPDATE parametros SET valor_parametro = " . $nroVta . " WHERE nombre_parametro='nro_orden_compra'";
             if (!mysql_query($sql)) {
                 die('Error: ' . mysql_error());
                 rollback();
                 break;
             } else {
                 commit();
                 return true;
             }
             return false;
         }
     } else {
         $sql = "delete from detalle_ordenes_compra where id_orden_compra=" . $oData["id_orden_compra"];
         getRS($sql);
         $sql = "delete from ordenes_compra where id_orden_compra=" . $oData["id_orden_compra"];
         getRS($sql);
         begin();
         $detalle = array();
         $cabecera = array();
         $cabecera = explode("@@", $oData["cabecera"]);
         $detalle = explode("||", $oData["detalle"]);
         $sql = "INSERT INTO  ordenes_compra (id_proveedor, fecha_orden_compra, nro_orden_compra, generada)\r\n\t\t\t\t\tVALUES (" . $cabecera[0] . ", '" . dateToMySQL($cabecera[1]) . "', " . $cabecera[2] . ", 1)";
         if (!mysql_query($sql)) {
             die('Error: ' . mysql_error());
             rollback();
             return false;
         } else {
             $id = mysql_insert_id();
             foreach ($detalle as $detail) {
                 $values = explode("@@", $detail);
                 $sql = "INSERT INTO detalle_ordenes_compra (id_orden_compra, id_producto, cantidad_detalle_orden_compra) VALUES  (" . $id . ", " . $values[0] . ", " . $values[1] . ")";
                 if (!mysql_query($sql)) {
                     die('Error: ' . mysql_error());
                     rollback();
                     break;
                 }
             }
             if ($cabecera[2]) {
                 $nroVta = $cabecera[2] + 1;
             }
             $sql = "UPDATE parametros SET valor_parametro = " . $nroVta . " WHERE nombre_parametro='nro_orden_compra'";
             if (!mysql_query($sql)) {
                 die('Error: ' . mysql_error());
                 rollback();
                 break;
             } else {
                 commit();
                 return true;
             }
             return false;
         }
     }
 }
示例#25
0
 function update()
 {
     if (!PRODUCTION) {
         // Don't want to ever run this in development
         die('good');
     }
     App::import('Vendor', 'bradleyboy/updater');
     $old_mask = umask(0);
     // Move these to off position in case we need to rollback
     $movers = array('app', 'm', 'cron.php', 'images.php', 'index.php', 'p.php', 'popup.php');
     foreach ($movers as $m) {
         $path = ROOT . DS . $m;
         $to = $path . '.off';
         if (is_dir($path)) {
             $f = new Folder($path);
             $f->move($to);
             if (is_dir($path)) {
                 umask($old_mask);
                 rollback($movers);
                 die('permfail');
             }
         } else {
             if (file_exists($path)) {
                 rename($path, $to);
                 if (file_exists($path)) {
                     umask($old_mask);
                     rollback($movers);
                     die('permfail');
                 }
             }
         }
     }
     $version = trim($this->Pigeon->version(true));
     if ((strpos($version, 'b') !== false || strpos($version, 'a') !== false) && BETA_TEST) {
         $core = 'http://www.sspdirector.com/zips/upgrade_beta.zip';
     } else {
         $core = 'http://www.sspdirector.com/zips/upgrade.zip';
     }
     $zip_helper = 'http://www.sspdirector.com/zips/pclzip.lib.txt';
     $local_core = ROOT . DS . 'core.zip';
     $local_helper = ROOT . DS . 'pclzip.lib.php';
     if (download_file($core, $local_core) && download_file($zip_helper, $local_helper)) {
         require $local_helper;
         $archive = new PclZip('core.zip');
         $archive->extract(PCLZIP_CB_POST_EXTRACT, 'extract_callback');
     } else {
         umask($old_mask);
         rollback($movers);
         die('permfail');
     }
     foreach ($movers as $m) {
         $path = ROOT . DS . $m;
         $to = $path . '.off';
         if (is_dir($to)) {
             $f = new Folder($path);
             $f->delete($to);
         } else {
             if (file_exists($to)) {
                 unlink($to);
             }
         }
     }
     unlink($local_core);
     unlink($local_helper);
     umask($old_mask);
     die('good');
 }
示例#26
0
    die("ERROR: Query failed for the list of comments: " . mysql_error($link));
}
if (mysql_num_rows($commentsResult) == 0) {
    printHTMLHighlighted("<h2>There is no comment for this user.</h2>\n");
} else {
    print "<p><DL>\n";
    printHTMLHighlighted("<h3>Comments about you.</h3>\n");
    while ($commentsRow = mysql_fetch_array($commentsResult)) {
        $authorId = $commentsRow["from_user_id"];
        $authorResult = mysql_query("SELECT nickname FROM users WHERE users.id={$authorId}", $link);
        if (!$authorResult) {
            error_log("[" . __FILE__ . "] Query 'SELECT nickname FROM users WHERE users.id={$authorId}' failed for the comment author: " . mysql_error($link));
            die("ERROR: Query failed for the comment author '{$authorId}': " . mysql_error($link));
        }
        if (mysql_num_rows($authorResult) == 0) {
            rollback($link);
            die("ERROR: This author '{$authorId}' does not exist.<br>\n");
        } else {
            $authorRow = mysql_fetch_array($authorResult);
            $authorName = $authorRow["nickname"];
        }
        $date = $commentsRow["date"];
        $comment = $commentsRow["comment"];
        print "<DT><b><BIG><a href=\"/PHP/ViewUserInfo.php?userId=" . $authorId . "\">{$authorName}</a></BIG></b>" . " wrote the " . $date . "<DD><i>" . $comment . "</i><p>\n";
        mysql_free_result($authorResult);
    }
    print "</DL>\n";
}
commit($link);
mysql_free_result($userResult);
mysql_free_result($commentsResult);
// dell'ultimo movimento
$query = "SELECT MAX(numero) AS n " . "FROM movimento";
$table = mysqli_query($conn, $query) or die(mysqli_error());
$row = mysqli_fetch_assoc($table);
if (!isset($row)) {
    $n = 1;
} else {
    $n = $row['n'] + 1;
}
mysqli_free_result($table);
// Inserisce i dati del movimento
$query = "INSERT INTO movimento (" . "numero, cc, tipo, importo) " . "VALUES (" . $n . ", " . $_GET['cc'] . ", " . "'" . $_GET['tipo'] . "', " . $_GET['importo'] . ")";
mysqli_query($conn, $query) or rollback($conn);
// Aggiorna il saldo
$query = "UPDATE conto_corrente " . "SET saldo = saldo " . ($_GET['tipo'] == 'prelievo' ? '- ' : '+ ') . $_GET['importo'] . " " . "WHERE numero = " . $_GET['cc'];
mysqli_query($conn, $query) or rollback($conn);
// Termina positivamente la transazione
$query = "COMMIT";
mysqli_query($conn, $query) or die(mysqli_error());
echo "<p>Situazione conto n.: " . $_GET['cc'] . "</p>\n";
$query = "SELECT cognome, nome FROM " . "correntista, conto_corrente WHERE " . "numero = " . $_GET['cc'] . " AND " . "correntista.id_correntista = conto_corrente.id_correntista";
$table = mysqli_query($conn, $query) or die(mysqli_error($conn));
$row = mysqli_fetch_assoc($table);
echo "<p>Intestatario: " . $row['cognome'] . " " . $row['nome'] . "</p>\n";
mysqli_free_result($table);
// Mostra il nuovo saldo
$query = "SELECT saldo FROM " . "conto_corrente WHERE " . "numero = " . $_GET['cc'];
$table = mysqli_query($conn, $query) or die(mysqli_error($conn));
$row = mysqli_fetch_assoc($table);
echo "<p>Saldo contabile: " . $row['saldo'] . "</p>\n";
mysqli_free_result($table);
 function executePolitica_SR()
 {
     $sql = "SELECT *\r\n\t\t\t\tFROM productos p\r\n\t\t\t\t  INNER JOIN agotamientos_permitidos ap\r\n\t\t\t\t\tON ap.id_agotamiento = p.id_agotamiento\r\n\t\t\t\tWHERE id_politica = 2";
     $rs = getRS($sql);
     if (getNrosRows($rs)) {
         $flag = false;
         while ($row = getRow($rs)) {
             $sql = "SELECT *\r\n\t\t\t\t\t\tFROM ordenes_compra oc\r\n\t\t\t\t\t\t  INNER JOIN detalle_ordenes_compra doc\r\n\t\t\t\t\t\t\tON doc.id_orden_compra = oc.id_orden_compra\r\n\t\t\t\t\t\t\t  AND id_producto = " . $row["id_producto"] . "\r\n\t\t\t\t\t\tORDER BY fecha_orden_compra DESC LIMIT 1";
             $rsOC = getRS($sql);
             $rowOC = getRow($rsOC);
             $fechaOC = $rowOC["fecha_orden_compra"];
             $fechaActual = date("Y-m-d");
             $diferencia = getDiferenciaEntreFechas($fechaOC, $fechaActual);
             $R = $row["tpo_de_reaprovisionamiento_producto"];
             if ($diferencia >= $R) {
                 $R = $R / 7;
                 // lo convierto a semanas
                 $A = $row["costo_de_emision_producto"];
                 $oData = array();
                 $oData["id_producto"] = $row["id_producto"];
                 $D = $this->getDemandaAnual($oData);
                 $H = $row["tasa_de_almacenamiento_producto"] * $row["precio_unitario_producto"];
                 $Q = number_format(sqrt(2 * $A * $D / $H));
                 $agotamiento = $row["agotamientos_perm_x_anio"];
                 $N = number_format($D / $Q);
                 $nivel_de_serv = 1 - $agotamiento / $N;
                 $k = $this->getFactorDeSeguridad($nivel_de_serv);
                 $data = $this->getMinTpoDeEntregaAndProv($oData);
                 $te = $data["tpo_de_entrega"];
                 $te_sobre_durEnSem = $te / $this->getDuracionPeriodoEnSemanas();
                 $days = number_format($te * 7 + $R);
                 $desv_std = $this->getDesvStd($oData, $days) * $te_sobre_durEnSem;
                 $SS = $k * $desv_std;
                 $mu_e = $this->getDemanda($oData, $days) * $te_sobre_durEnSem;
                 $S = number_format($mu_e + $SS);
                 if ($row["stock_actual_producto"] < $S) {
                     begin();
                     $sql = "UPDATE productos SET nivel_s_producto={$S}, stock_seguridad_producto={$SS} WHERE id_producto=" . $oData["id_producto"];
                     if (!getRS($sql)) {
                         rollback();
                         return false;
                     } else {
                         $exp = new ExpertoOrdenes();
                         $nro_orden = $exp->getNroOrdenCompra();
                         $sql = "INSERT INTO  ordenes_compra (fecha_orden_compra, nro_orden_compra, generada, id_proveedor)\r\n\t\t\t\t\t\t\t\t\tVALUES ('" . date("Y-m-d") . "', " . $nro_orden . ", 0, " . $data["id_proveedor"] . ")";
                         if (!getRS($sql)) {
                             rollback();
                             return false;
                         } else {
                             $id = mysql_insert_id();
                             $cant = $S - $row["stock_actual_producto"];
                             $sql = "INSERT INTO detalle_ordenes_compra (id_orden_compra, id_producto, cantidad_detalle_orden_compra) VALUES  (" . $id . ", " . $oData["id_producto"] . ", " . $cant . ")";
                             if (!getRS($sql)) {
                                 rollback();
                                 return false;
                             } else {
                                 $nro_orden += 1;
                                 $sql = "UPDATE parametros SET valor_parametro = " . $nro_orden . " WHERE nombre_parametro='nro_orden_compra'";
                                 if (!mysql_query($sql)) {
                                     die('Error: ' . mysql_error());
                                     rollback();
                                     return false;
                                 } else {
                                     commit();
                                     $flag = true;
                                 }
                             }
                         }
                     }
                 }
             }
         }
         return $flag;
     }
     return false;
 }