/** * @param string $sql * @param array $queryParams * * @return bool|\mysqli_result * @throws Mysql */ public function execute(string $sql, $queryParams = []) { // log the query $this->log_sql($sql, $queryParams); // start sql transaction $this->mysqli->begin_transaction(); // use cache to get prepared statement $statement = $this->get_statement_from_sql($sql); // bind params if (is_array($queryParams) && !empty($queryParams)) { $bindTypes = ''; foreach ($queryParams as $name => $value) { $bindTypes .= static::get_bind_type($value); } $statement->bind_param($bindTypes, ...$queryParams); } // execute statement if (!$statement->execute()) { $this->mysqli->rollback(); throw new Mysql($statement->error, $statement->errno, null, $sql); } // commit this transaction $this->mysqli->commit(); // save info for latest query $this->insertId = $statement->insert_id; $this->affectedRows = $statement->affected_rows; return $statement->get_result(); }
/** * commit transaction */ public function commit() { if ($this->connection === null) { $this->open(); } $this->connection->commit(); $this->connection->autocommit(true); }
function modificaAlumno($alumno) { global $servidor, $bd, $usuario, $contrasenia; try { @($db = new mysqli($servidor, $usuario, $contrasenia)); if (mysqli_connect_errno() != 0) { throw new Exception('Error conectando:' . mysqli_connect_error(), mysqli_connect_errno()); } $db->select_db($bd); if ($db->errno != 0) { throw new Exception('Error seleccionando bd:' . $db->error, $db->errno); } $consulta = "update alumnos set password='******', nombre='" . $alumno->nombre . "', apellido='" . $alumno->apellido . "', dni='" . $alumno->dni . "', email='" . $alumno->email . "', telefono=" . $alumno->telefono . ", sexo='" . $alumno->sexo . "' where login='******'"; if ($db->query($consulta) === false) { throw new ExcepcionEnTransaccion(); } $db->commit(); $db->close(); } catch (ExcepcionEnTransaccion $e) { echo 'No se ha podido realizar la modificacion'; $db->rollback(); $db->close(); } catch (Exception $e) { echo $e->getMessage(); if (mysqli_connect_errno() == 0) { $db->close(); } exit; } }
function modificaCoche($coche) { //alert($coche->login); global $servidor, $bd, $usuario, $contrasenia; try { @($db = new mysqli($servidor, $usuario, $contrasenia)); if (mysqli_connect_errno() != 0) { throw new Exception('Error conectando:' . mysqli_connect_error(), mysqli_connect_errno()); } $db->select_db($bd); if ($db->errno != 0) { throw new Exception('Error seleccionando bd:' . $db->error, $db->errno); } $consulta = "update coches set marca='" . $coche->marca . "', modelo='" . $coche->modelo . "', color='" . $coche->color . "' where matricula='" . $coche->matricula . "'"; if ($db->query($consulta) === false) { throw new ExcepcionEnTransaccion(); } $db->commit(); $db->close(); } catch (ExcepcionEnTransaccion $e) { echo 'No se ha podido realizar la modificacion'; $db->rollback(); $db->close(); } catch (Exception $e) { echo $e->getMessage(); if (mysqli_connect_errno() == 0) { $db->close(); } exit; } }
public function commit() { if ($this->logger != null) { $this->logger->log(Logger::LEVEL_TRACE, __FUNCTION__." called"); } return $this->conn->commit(); }
function commit() { $this->in_transaction--; if ($this->in_transaction == 0) { parent::commit(); } return $this->in_transaction; }
/** * Commit */ public function commit() { if (!$this->resource) { $this->connect(); } $this->resource->commit(); $this->inTransaction = false; }
/** * Commits a transaction. * * @return Boolean */ public function commit() { $this->connect(); if ($this->connected === TRUE) { return $this->mysqli->commit(); } return FALSE; }
/** * Commits pending DB transactions. * * @return bool true on success */ public function commit() { $startTime = microtime(true); $ret = $this->db->commit(); //gather stats about queries $this->addQueryTime(microtime(true) - $startTime); return $ret; }
/** * Commit the transaction * @throws MysqltcsException on commit error */ public function commit() { if ($this->mysqliRef->commit()) { $this->log("commit"); return; } $mex = "Mysql error: it is not possible perform the commit. " . $this->mysqliRef->error; $this->log($mex); throw new MysqltcsException($mex); }
/** * {@inheritDoc} */ public function commit() { if (!$this->isConnected()) { $this->connect(); } $this->resource->commit(); $this->inTransaction = false; $this->resource->autocommit(true); return $this; }
/** * Method to commit a transaction. * * @param boolean $toSavepoint If true, commit to the last savepoint. * * @return void * * @since 1.0 * @throws \RuntimeException */ public function transactionCommit($toSavepoint = false) { if (!$toSavepoint || $this->transactionDepth <= 1) { $this->connect(); if ($this->connection->commit()) { $this->transactionDepth = 0; } return; } $this->transactionDepth--; }
/** * Commit a transaction. If we're not in transaction, throw an exception. * It's important that the calling code knows it's not in a transaction if * the developer assumed that they were. * * @todo Are we scared that bol_in_transaction might get out of sync and * prevent legit commits? * * @return \Docnet\DB * @throws \Exception if we're not in a transaction * @throws \Exception if the driver reports that the commit failed */ public function commit() { if (!$this->bol_in_transaction) { throw new \Exception("Not in a transaction, can't commit"); } if (!$this->obj_db->commit()) { throw new \Exception("MySQL failed to commit the transaction"); } $this->bol_in_transaction = false; return $this; }
public function commit() { if ($this->transactionCount == 0) { return false; } if ($this->transactionCount == 1) { $result = @$this->mysqli->commit(); } else { $result = @$this->mysqli->query('RELEASE SAVEPOINT point' . ($this->transactionCount - 1)); } $this->popTransaction(); return $result; }
function db_insert($insert_query) { // Instantiate the mysqli class $mysqli = new mysqli(); //Provide your DB credentials here // Connect to the database server and select a database $mysqli->connect('your db server', 'your db id', 'your password', 'your db name'); //Execute query $result = $mysqli->query($insert_query); //commit $commit = $mysqli->commit(); // Close the connection $mysqli->close(); }
function social_worker_login($login_container) { //Create a container object which will hold complete information required to display the complete order page $container = new stdClass(); //Establish mysqli connection $mysqli_connection = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE); if ($mysqli_connection->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli_connection->connect_errno . ") " . $mysqli_connection->connect_error; $container->show_failure_message = true; $container->destination_page = LOGIN_PAGE; return $container; } //Set auto-commit to FALSE explicitly if (!$mysqli_connection->autocommit(FALSE)) { echo "Failed to turn off auto-commit to false"; } $sw_details_info_do = new SocialWorkerDetailsDO(); $sw_details_info_access = new SocialWorkerDetailsAccess($mysqli_connection); $sw_details_info_do = $sw_details_info_access->load_by_sw_details_phonenumber($login_container->login_username); //Validate whether order loading is successful or not. if ($sw_details_info_access->m_status == false || $sw_details_info_access->m_status_code == STATUS_FETCH_NO_DATA) { echo "Failed to load Admin details for the Admin User Name - " . $admin_login_container->user_name; $container->show_failure_message = true; $container->destination_page = LOGIN_PAGE; //Close the connection $mysqli_connection->close(); return $container; } //Password Validation if (!strcmp($sw_details_info_do->password, $login_container->password)) { echo "User Authentication Successful."; } else { echo "User Authentication Failed. Password Mismatch."; $container->show_failure_message = true; $container->destination_page = ADMIN_LOGIN_PAGE; //Close the connection $mysqli_connection->close(); return $container; } $container->sw_user_loggedin = true; $container->sw_user_name = $sw_details_info_do->m_name; //everything is fine $mysqli_connection->commit(); //Close the connection $mysqli_connection->close(); return $container; }
/** * @param mysqli $db * @param int $epoch */ function cleanChallenges($db, $epoch = NULL) { global $MAXCHALLENGELIFETIME; if ($epoch === NULL) { $epoch = time(); } $cutoff = $epoch - $MAXCHALLENGELIFETIME; if ($stmt = $db->prepare('DELETE FROM challenges WHERE `epoch` < ?')) { $stmt->bind_param("i", $cutoff); if ($stmt->execute()) { $db->commit(); } else { $db->rollback(); // Don't report, this is just maintenance. } } }
/** * Inserts a new order into the orders DB * * @param $orderinfo * @param $cart * @param $username * @return order ID, or FALSE on failure */ function insertOrder($orderinfo, $cart, $username) { if (!$orderinfo || !$cart || !$username) { return FALSE; } include 'db_info.php'; //include('userfunctions.php'); @($db = new mysqli($dbhost, $dbuser, $dbpassword, $dbname)); if (mysqli_connect_errno()) { echo "<br><h2 style='color:red'>Database connection error.</h2><br>" . mysqli_connect_error(); return FALSE; } extract($orderinfo); // $orderinfo["addr"] = $addr // Only store the last 4 digits of cards in the db $cardnumber = substr($cardnumber, -4); $db->autocommit(FALSE); // Partial commits are bad $query = "INSERT INTO orders (shipping_addr, shipping_city, shipping_state, shipping_zip, creditcard, shipping_cost, ordertotal) VALUES \r\n\t\t ('" . addslashes($addr) . "', '" . addslashes($city) . "', '" . addslashes($state) . "', '" . addslashes($zip) . "', '" . $cardnumber . "', '" . $shipping . "', '" . $total . "');"; $result = $db->query($query); if (!$result) { return FALSE; } $orderid = $db->insert_id; $query = "INSERT INTO user_orders (username, orderid) VALUES ('" . addslashes($username) . "', '" . $orderid . "');"; $result = $db->query($query); if (!$result) { return FALSE; } foreach ($cart as $pid => $qty) { $product = getProductInfo($pid); $curprice = $product["price"]; $query = "INSERT INTO product_orders (orderid, pid, qty, purchaseprice) VALUES \r\n\t\t\t\t('" . $orderid . "', '" . $pid . "', '" . $qty . "', '" . $curprice . "');"; $result = $db->query($query); if (!$result) { return FALSE; } } $db->commit(); $db->autocommit(TRUE); $db->close(); return $orderid; }
function compraProdotto($id, $email) { $mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME); $mysqli->autocommit(false); $add = $mysqli->query("INSERT INTO ordini (id_prodotto, nomeutente) VALUES ({$id}, '{$email}')"); $q = $mysqli->query("SELECT * FROM prodotti WHERE id={$id}"); if (!$add) { $mysqli->rollback(); return false; } $prodottoSelezionato = mysqli_fetch_assoc($q); if ($prodottoSelezionato['quantita'] == 0) { $mysqli->rollback(); return false; } $nuovaQuantita = $prodottoSelezionato['quantita'] - 1; $u = $mysqli->query("UPDATE prodotti SET quantita = {$nuovaQuantita} WHERE id={$id}"); if ($u) { $mysqli->commit(); $mysqli->autocommit(true); return true; } }
<?php $mysqli = new mysqli("localhost", "xjun", "999999/aBc", "test"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit; } /* disable autocommit */ $mysqli->autocommit(FALSE); $mysqli->query("CREATE TABLE myCity LIKE City"); $mysqli->query("ALTER TABLE myCity Type=InnoDB"); $mysqli->query("INSERT INTO myCity SELECT * FROM City LIMIT 50"); /* commit insert */ $mysqli->commit(); /* delete all rows */ $mysqli->query("DELETE FROM myCity"); if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) { $row = $result->fetch_row(); printf("%d rows in table myCity.\n", $row[0]); /* Free result */ $result->close(); } /* Rollback */ $mysqli->rollback(); if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) { $row = $result->fetch_row(); printf("%d rows in table myCity (after rollback).\n", $row[0]); /* Free result */ $result->close(); }
/** * {@inheritdoc} */ public function commit() { return $this->_conn->commit(); }
/** * Transaction commit * * @uses mysqli->commit(); * @uses mysqli->autocommit(true); */ public function commit() { $this->_mysqli->commit(); $this->_transaction_in_progress = false; $this->_mysqli->autocommit(true); }
$modelo = $_POST['modelo']; $color = $_POST['color']; try { @($db = new mysqli($servidor, $usuario, $contrasenia)); if (mysqli_connect_errno() != 0) { throw new Exception('Error conectando:' . mysqli_connect_error(), mysqli_connect_errno()); } $db->select_db($bd); if ($db->errno != 0) { throw new Exception('Error seleccionando bd:' . $db->error, $db->errno); } $consulta = "update coches set marca='" . $marca . "', modelo='" . $modelo . "', color='" . $color . "' where matricula='" . $matricula . "'"; if ($db->query($consulta) === false) { throw new ExcepcionEnTransaccion(); } $db->commit(); header("Location:../../index.php?controlador=coches&accion=listar"); $db->close(); } catch (ExcepcionEnTransaccion $e) { echo 'No se ha podido realizar la modificacion'; $db->rollback(); $db->close(); } catch (Exception $e) { echo $e->getMessage(); if (mysqli_connect_errno() == 0) { $db->close(); } exit; } } ?>
function save_image() { include "dbconfig.php"; // normally this info would be pulled from a database. // build JSON array. // 1. 업로드 파일 존재여부 확인 if (!isset($_FILES['image'])) { exit("업로드 파일 존재하지 않음"); } // if // 2. 업로드 오류여부 확인 if ($_FILES['image']['error'] > 0) { switch ($_FILES['image']['error']) { case 1: exit("php.ini 파일의 upload_max_filesize 설정값을 초과함(업로드 최대용량 초과)"); case 2: exit("Form에서 설정된 MAX_FILE_SIZE 설정값을 초과함(업로드 최대용량 초과)"); case 3: exit("파일 일부만 업로드 됨"); case 4: exit("업로드된 파일이 없음"); case 6: exit("사용가능한 임시폴더가 없음"); case 7: exit("디스크에 저장할수 없음"); case 8: exit("파일 업로드가 중지됨"); default: exit("시스템 오류가 발생"); } // switch } // if // 3. 업로드 제한용량 체크(서버측에서 8M로 제한) if ($_FILES['image']['size'] > 8388608) { exit("업로드 최대용량 초과"); } // if // 4. 업로드 허용 확장자 체크(보편적인 jpg,jpeg,gif,png,bmp 확장자만 필터링) $ableExt = array('jpg', 'jpeg', 'gif', 'png', 'bmp'); $path = pathinfo($_FILES['image']['name']); $ext = strtolower($path['extension']); if (!in_array($ext, $ableExt)) { exit("허용되지 않는 확장자입니다."); } // if // 5. MIME를 통해 이미지파일만 허용(2차 확인) // $ableImage = array('image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png', 'image/gif','image/bmp','image/pjpeg'); // if(!in_array($_FILES['image']['type'], $ableImage)) { // exit("지정된 이미지만 허용됩니다."); // }//if // 6. DB에 저장할 이미지 정보 가져오기(width,height 값 활용) $img_size = getimagesize($_FILES['image']['tmp_name']); // DB연결 $mysqli = new mysqli($dbhost, $dbusr, $dbpass, $dbname); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } $create_table = "CREATE TABLE if not exists image_files( \n\t\t\t\t\tid int auto_increment, \n\t\t\t\t\tupload_filename varchar(100), \n\t\t\t\t\tdb_filename varchar(100), \n\t\t\t\t\tfilepath varchar(100), \n\t\t\t\t\tfilesize int(8),\n\t\t\t\t\tfile_type VARCHAR(40),\n\t\t\t\t\tupload_date DATETIME DEFAULT CURRENT_TIMESTAMP,\n\t\t\t\t\twidth int(8), \n\t\t\t\t\theight int(8), \n\t\t\t\t\tPRIMARY KEY (id) \n\t\t\t\t\t);"; $mysqli->query($create_table); // do~while: 새로만든 파일명이 중복일경우 반복하기 위한 루틴 do { // 6. 새로운 파일명 생성(마이크로타임과 확장자 이용) $time = explode(' ', microtime()); $fileName = $time[1] . substr($time[0], 2, 6) . '.' . strtoupper($ext); // 중요 이미지의 경우 웹루트(www) 밖에 위치할 것을 권장(예제 편의상 아래와 같이 설정) $filePath = $_SERVER['DOCUMENT_ROOT'] . '/web_test/image_test/upload_image/'; // 7. 생성한 파일명이 DB내에 존재하는지 체크 $query = sprintf("SELECT no FROM image_files WHERE db_filename = '%s'", $fileName); $result = $mysqli->query($query); if ($result === NULL) { break; } // 생성한 파일명이 중복하는 경우 새로 생성해서 체크를 반복(동시저장수가 대량이 아닌경우 중복가능 희박) } while ($result != NULL && $result->num_rows > 0); // db에 저장할 정보 가져옴 $upload_filename = $mysqli->real_escape_string($_FILES['image']['name']); $file_size = $_FILES['image']['size']; $file_type = $_FILES['image']['type']; $upload_date = date("Y-m-d H:i:s"); // $ip = $_SERVER['REMOTE_ADDR']; // 오토커밋 해제 $mysqli->autocommit(false); // 8. db에 업로드 파일 및 새로 생성된 파일정보등을 저장 $query = sprintf("INSERT INTO image_files\n\t\t(upload_filename,db_filename,filepath,filesize,file_type,upload_date,width,height) \n\t\tVALUES ('%s','%s','%s','%s','%s','%s',%d,%d)", $upload_filename, $fileName, $filePath, $file_size, $file_type, $upload_date, $img_size[0], $img_size[1]); $mysqli->query($query); if ($mysqli->error) { echo "Failed to insert image db: (" . $mysqli->error . ") "; } $insert_id = $mysqli->insert_id; // DB에 파일내용 저장 성공시 if ($mysqli->affected_rows > 0) { // 9. 업로드 파일을 새로 만든 파일명으로 변경 및 이동 if (move_uploaded_file($_FILES['image']['tmp_name'], $filePath . $fileName)) { // 10. 성공시 db저장 내용을 적용(커밋) $mysqli->commit(); } else { // 실패시 db에 저장했던 내용 취소를 위한 롤백 $mysqli->rollback(); exit("업로드 실패"); } // if } // if $image_saving_info = array("id" => $insert_id); $mysqli->close(); return $image_saving_info; }
<?php require_once "connect.inc"; $tmp = NULL; $link = NULL; $mysqli = new mysqli(); if (!is_null($tmp = @$mysqli->commit())) { printf("[013] Expecting NULL got %s/%s\n", gettype($tmp), $tmp); } if (!($mysqli = new my_mysqli($host, $user, $passwd, $db, $port, $socket))) { printf("[001] Cannot connect to the server using host=%s, user=%s, passwd=***, dbname=%s, port=%s, socket=%s\n", $host, $user, $db, $port, $socket); } if (true !== ($tmp = $mysqli->commit())) { printf("[002] Expecting boolean/true got %s/%s\n", gettype($tmp), $tmp); } if (true !== ($tmp = $mysqli->autocommit(false))) { printf("[003] Cannot turn off autocommit, expecting true, got %s/%s\n", gettype($tmp), $tmp); } if (!$mysqli->query('DROP TABLE IF EXISTS test')) { printf("[004] [%d] %s\n", $mysqli->errno, $mysqli->error); } if (!$mysqli->query('CREATE TABLE test(id INT) ENGINE = InnoDB')) { printf("[005] Cannot create test table, [%d] %s\n", $mysqli->errno, $mysqli->error); } if (!$mysqli->query('INSERT INTO test(id) VALUES (1)')) { printf("[006] [%d] %s\n", $mysqli->errno, $mysqli->error); } $tmp = $mysqli->commit(); if ($tmp !== true) { printf("[007] Expecting boolean/true, got %s/%s\n", gettype($tmp), $tmp); }
die("Connection failed: " . $conn->connect_error); } $sql = "SELECT userid FROM users WHERE email='" . $_POST["email"] . "' OR userid='" . $user . "'"; $result = $conn->query($sql); if ($result->num_rows > 0) { $error = "Error: Email or Username already exists<br/>"; } else { $row = $result->fetch_assoc(); $conn->autocommit(FALSE); $stmt = $conn->prepare("INSERT INTO users (userid,firstname,lastname,email,picture,sex,birthday,password) VALUES (?,?,?,?,?,?,?,?)"); if ($stmt === FALSE) { $error = "Failed to prepare statement<br/>"; } else { $stmt->bind_param("sssssiss", $user, $first, $last, $email, $picture, $sex, $dob, $pswd); $stmt->execute(); $conn->commit(); $stmt->close(); setcookie("loggedInUID", $user, time() + 60 * 60 * 24 * 30); } } $conn->close(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Registration</title> <link href="favicon.ico" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width" />
/** * {@inheritDoc} */ protected function realCommit() { $this->link->commit(); $this->link->autocommit(true); return $this; }
function confirmUser() { $args = func_get_args(); $email = $this->origRegInfo['s_email']; try { $mysqli = new mysqli($this->system_dbhost, $this->system_dbuser, $this->system_dbpass, $this->system_dbname); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit; } /* Prepare a select statement */ $query = "UPDATE `user` SET `isconfirmed`='Y' WHERE `email`='" . $email . "';"; $mysqli->query($query); $mysqli->commit(); $mysqli->close(); return true; } catch (Exception $e) { die($e->getMessage()); } }
public function commit() { parent::commit(); $this->autocommit(true); }
} else { echo "Invalid User!"; } require_once "db_connect.php"; $connection = new mysqli($db_hostname, $db_username, $db_password, $db_database); if ($connection->connect_error) { die(connect_error); } if (isset($_GET['submit'])) { $password1 = $_GET["password1"]; $password2 = $_GET["password2"]; if (!empty($password1) && !empty($password2)) { if ($password1 == $password2) { $query = "update user_pwd set password='******' where user_id='{$user_id}'"; $result = $connection->query($query); $connection->commit(); mysqli_close($connection); if ($result) { session_destroy(); header('Location: index.html'); } else { echo "Password not changed!"; } //sleep(5); } else { echo " Password not equal!"; } } else { echo " Password can not be empty!"; } }