function handleEditPage() { include_once 'login.php'; include_once 'showEventFunction.php'; $backURL = "<br/><a href = \"index.php\">Back to Home</a>"; // client side validation, if error, disable submit // if form is set and not empty, continue $showError = true; $errOutput = isFormFilled($showError); if ($errOutput) { $output = "<h1>Error</h1>"; return $output . $errOutput . $backURL; } $event = array(); $errMsg = array(); // prevent sql injection & data sanitize foreach ($_POST as $field => $value) { $event[$field] = sanitizeData($value); } include_once 'database_conn.php'; $columnLengthSql = "\n\t\tSELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH\n\t\tFROM INFORMATION_SCHEMA.COLUMNS\n\t\tWHERE TABLE_NAME = 'te_events'\n\t\tAND (column_name = 'eventTitle'\n\t\tOR column_name = 'eventDescription')"; //, DATA_TYPE $COLUMN_LENGTH = getColumnLength($conn, $columnLengthSql); // check data type and length validation $isError = false; $errMsg[] = validateStringLength($event['title'], $COLUMN_LENGTH['eventTitle']); //title $errMsg[] = validateStringLength($event['desc'], $COLUMN_LENGTH['eventDescription']); //desc $errMsg[] = validateDate($event['startTime']); //startTime $errMsg[] = validateDate($event['endTime']); //endTime $errMsg[] = validateDecimal($event['price']); //price for ($i = 0; $i < count($errMsg); $i++) { if (!($errMsg[$i] === true)) { $pageHeader = "Error"; $output = "<h1>{$pageHeader}</h1>"; $output . "{$errMsg[$i]}"; $isError = true; } } //if contain error, halt continue executing the code if ($isError) { return $output . $backURL; } // prepare sql statement $sql = "UPDATE te_events SET \n\t\teventTitle=?, eventDescription=?, \n\t\tvenueID=?, catID=?, eventStartDate=?, \n\t\teventEndDate=?, eventPrice=? WHERE eventID=?;"; $stmt = mysqli_prepare($conn, $sql); mysqli_stmt_bind_param($stmt, "ssssssss", $event['title'], $event['desc'], $event['venue'], $event['category'], $event['startTime'], $event['endTime'], $event['price'], $event['e_id']); // execute update statement mysqli_stmt_execute($stmt); // check is it sucess update if (mysqli_stmt_affected_rows($stmt)) { $output = "<h1>{$event['title']} was successfully updated.</h1>"; return $output . $backURL; } else { $output = "<h1>Nothing update for {$event['title']}</h1>"; return $output . $backURL; } echo "<br/>"; return; }
public function affectedRows() { return \mysqli_stmt_affected_rows($this->res); }
function add_one($data_add) { $query = "INSERT INTO `{$this->_table}` SET `author` = ?"; $stmt = mysqli_prepare($this->_c, $query); if ($stmt) { mysqli_stmt_bind_param($stmt, 's', $data_add); mysqli_stmt_execute($stmt); } return printf("Rows inserted: %d\n", mysqli_stmt_affected_rows($stmt)); }
function mysqli_update($db, string $sql, ...$params) : int { $stmt = mysqli_interpolate($db, $sql, ...$params); if (!mysqli_stmt_execute($stmt)) { throw new mysqli_sql_exception(mysqli_stmt_error($stmt), mysqli_stmt_errno($stmt)); } $affected = mysqli_stmt_affected_rows($stmt); mysqli_stmt_close($stmt); return $affected; }
function mysqli_update($db, $sql) { $stmt = call_user_func_array('mysqli_interpolate', func_get_args()); if (!mysqli_stmt_execute($stmt)) { throw new mysqli_sql_exception(mysqli_stmt_error($stmt), mysqli_stmt_errno($stmt)); } $affected = mysqli_stmt_affected_rows($stmt); mysqli_stmt_close($stmt); return (int) $affected; }
function model_delete($id) { global $l; $query = 'DELETE FROM areinman__kaubad WHERE Id=? LIMIT 1'; $stmt = mysqli_prepare($l, $query); mysqli_stmt_bind_param($stmt, 'i', $id); mysqli_stmt_execute($stmt); $deleted = mysqli_stmt_affected_rows($stmt); mysqli_stmt_close($stmt); return $deleted; }
/** * @param $connection * @param array $user * @return bool */ function saveUser($connection, array &$user) { $query = 'INSERT IGNORE INTO users (name, email, hashed_password) VALUES (?, ?, ?)'; $statement = mysqli_prepare($connection, $query); mysqli_stmt_bind_param($statement, 'sss', $user['name'], $user['email'], $user['hashed_password']); mysqli_stmt_execute($statement); $inserted = (bool) mysqli_stmt_affected_rows($statement); if ($inserted) { $user['id'] = mysqli_stmt_insert_id($statement); } mysqli_stmt_close($statement); return $inserted; }
function add_one($array) { $query = "INSERT INTO `{$this->_table}` SET `{$this->_fields_aut}` = ?"; $stmt = mysqli_prepare($this->_c, $query); if ($stmt) { $count = count($data_add); for ($i = 0; $i < $count; $i++) { mysqli_stmt_bind_param($stmt, 's', $data_add[$i]); mysqli_stmt_execute($stmt); } } return printf("Rows inserted: %d\n", mysqli_stmt_affected_rows($stmt)); mysqli_stmt_close($stmt); }
function create_cookie($dbc, $username) { $create_token = "INSERT INTO tokens (username, token) VALUES (?, ?)"; $stmt = mysqli_prepare($dbc, $create_token); $token = password_hash($username . "pickem", PASSWORD_DEFAULT); mysqli_stmt_bind_param($stmt, "ss", $username, $token); mysqli_stmt_execute($stmt); $affected_rows = mysqli_stmt_affected_rows($stmt); if ($affected_rows == 1) { setcookie("username", $username); setcookie("auth_token", $token); } mysqli_stmt_close($stmt); }
/** * Kustutab valitud rea andmebaasist. * * @param int $id Kustutatava rea ID * * @return int Mitu rida kustutati */ function model_delete($id) { global $l, $prefix; $query = 'DELETE FROM ' . $prefix . '__kaubad WHERE Id=? LIMIT 1'; $stmt = mysqli_prepare($l, $query); if (mysqli_error($l)) { echo mysqli_error($l); exit; } mysqli_stmt_bind_param($stmt, 'i', $id); mysqli_stmt_execute($stmt); $deleted = mysqli_stmt_affected_rows($stmt); mysqli_stmt_close($stmt); return $deleted; }
function versionsinsert($stmt) { global $style, $lowbeam, $lbtech, $highbeam, $hbtech; mysqli_stmt_bind_param($stmt, "sssss", $style, $lowbeam, $lbtech, $highbeam, $hbtech); mysqli_stmt_execute($stmt); $affected_rows = mysqli_stmt_affected_rows($stmt); if ($affected_rows == 1) { echo 'Headlamp Entered'; mysqli_stmt_close($stmt); mysqli_close($dbc); } else { echo 'Error Occurred <br/>'; echo mysqli_error(); mysqli_stmt_close($stmt); mysqli_close($dbc); } }
function verify($uuid) { $msconf = getDatabaseCredentials(); $dbcon = mysqli_connect($msconf['host'], $msconf['user'], $msconf['pass'], $msconf['db']); if (mysqli_connect_errno($dbcon)) { echo "Failed to connect to MySQL: " . mysqli_connect_errno($dbcon) . " : " . mysqli_connect_error(); die; } $dbcon->query('CREATE TABLE IF NOT EXISTS `Users` (`Username` varchar(16) NOT NULL, `Name` varchar(60) NOT NULL, `PassHash` varchar(256) NOT NULL, `APIKey` varchar(256) NULL, `Permission` varchar(2) NOT NULL DEFAULT \'NN\', UNIQUE KEY `Username` (`Username`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;'); $dbcon->query('CREATE TABLE IF NOT EXISTS `Blog` (`PUID` varchar(200) NOT NULL,`Post` varchar(10000) NOT NULL,`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `Author` varchar(16) NOT NULL, `Title` varchar(60) NOT NULL, UNIQUE KEY `PUID` (`PUID`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;'); $dbcon->query('INSERT INTO `Users` (`Username`, `Name`, `PassHash`, `Permission`) VALUES (\'ace\', \'Cory Redmond\', \'2y11$WULjGCfjZEvtGEXfZkL3G.uzF3fRlJPGVsR.jCGguRhKIuph28572\', \'YY\');'); // Default database connect // $preparedStm = $dbcon->prepare("UPDATE `Users` SET `Verified`='Y' WHERE `Verified` = ?;"); $preparedStm->bind_param("s", $uuid); $preparedStm->execute(); $aff = mysqli_stmt_affected_rows($preparedStm); if ($aff > 0) { return true; } return false; }
function customerInsert($data) { $dbh = @mysqli_connect($servername, $username, $password, $dbname); if (!$dbh) { die(mysqli_connect_error()); } $sql = "INSERT INTO customers (custid, firstname, lastname, email, company, phone, comment) VALUES (NULL, ?, ?, ?, ?, ?, ?)"; $stmt = mysqli_prepare($dbh, $sql); mysqli_stmt_bind_param($stmt, "sssssss", $data["firstname"], $data["lastname"], $data["email"], $data["company"], $data["phone"], $data["comment"]); mysqli_stmt_execute($stmt); print "Rows inserted: " . mysqli_stmt_affected_rows($stmt) . "<br />"; // printf("Error: %s.\n", mysqli_stmt_error($stmt)); /* if(mysqli_stmt_execute($stmt)){ print "customerInsert().executed<br />"; print("Rows inserted: " . mysqli_stmt_affected_rows($stmt)); } */ $error = mysqli_connect_error($dbh); mysqli_close($dbh); return $error; }
function customerInsert($data) { print "customerInsert().start<br />"; $dbh = @mysqli_connect("localhost", "root", "", "custorders"); if (!$dbh) { die(mysqli_connect_error()); } print "customerInsert().connected<br />"; $sql = "INSERT INTO customers (custid, fname, lname, address, city, prov, post, phone) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)"; $stmt = mysqli_prepare($dbh, $sql); mysqli_stmt_bind_param($stmt, "sssssss", $data["fname"], $data["lname"], $data["address"], $data["city"], $data["prov"], $data["post"], $data["phone"]); mysqli_stmt_execute($stmt); print "Rows inserted: " . mysqli_stmt_affected_rows($stmt) . "<br />"; // printf("Error: %s.\n", mysqli_stmt_error($stmt)); /* if(mysqli_stmt_execute($stmt)){ print "customerInsert().executed<br />"; print("Rows inserted: " . mysqli_stmt_affected_rows($stmt)); } */ $error = mysqli_error($dbh); mysqli_close($dbh); return $error; }
function customerInsert($data) { // this is the SQL code to use for your DB. You could type this out or, in this case, add a dummy row through phpmyadmin, and copy the // code from there $sql = "INSERT INTO customers (CustomerId, CustFirstName, CustLastName, CustAddress, CustCity, CustProv, CustPostal, CustCountry, CustHomePhone, CustBusPhone, CustEmail, AgentId) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; // this is the connection to your DB. $dbh is a variable to save the information of mysqli_connect. You could store the login information // into variables - $server, $username, $password, $tableToBeEditted $dbh = mysqli_connect("localhost", "travel", "password", "travelexperts"); // if the connection fails... if (!$dbh) { // return the connection error and exit function. return mysqli_connect_error(); } // this is preparing a variable with the parameters needed to INSERT info. // $dbh is the connection being used. // $sql is the code needed to change your DB table $stmt = mysqli_prepare($dbh, $sql); // mysqli_stmt_bind_param takes the prepared variable ($stmt) with the connection and SQL code, and replace the ? with the array data. // It uses the 'sssssssssi' as the types information being passed. mysqli_stmt_bind_param($stmt, "ssssssssssi", $data['CustFirstName'], $data['CustLastName'], $data['CustAddress'], $data['CustCity'], $data['CustProv'], $data['CustPostal'], $data['CustCountry'], $data['CustHomePhone'], $data['CustBusPhone'], $data['CustEmail'], $data['AgentId']); // execute all the above steps. mysqli_stmt_execute($stmt); // if the number of rows change... if (mysqli_stmt_affected_rows($stmt)) { // this returns different values for success and failures. 1 means success and 0 or -1 are failures. // print this message. This says that rows have changed, but doesn't tell you of it worked properly. Needs to be a 1 not 0 or-1 $message = "Customer added successfully!"; } else { // this will print if nothing has change or mysqli_stmt_affected_rows returns a 0. $message = "Adding Customer Failed. Call Technical Support"; } // always close your table and DB so that it can be accessed by others. mysqli_close($dbh); // return the message return $message; }
function db_vexec($query, $args) { $stmt = db_vce_stmt($query, $args); if (($affected_rows = mysqli_stmt_affected_rows($stmt)) < 0) fatal_mysqli('mysqli_affected_rows'); mysqli_stmt_close($stmt); return $affected_rows; }
$scrubbed = array_map("spam_scrubber", $_POST); // Handle the form if (!empty($scrubbed["gbComment"])) { // Create the query $gb_query = "INSERT INTO guestbook (gbName, gbEmail, gbComment, gbDateAdded) VALUES (?, ?, ?, NOW())"; // Prepare the statement $stmt = mysqli_prepare($li, $gb_query); // Bind the variables: mysqli_stmt_bind_param($stmt, 'sss', $name, $email, $comment); // Assign values to the variables $name = $scrubbed["gbName"]; $email = $scrubbed["gbEmail"]; $comment = $scrubbed["gbComment"]; // Execute the query mysqli_stmt_execute($stmt); $res = mysqli_stmt_affected_rows($stmt); // See if insert was successful or not if ($res == 1) { $ret_str = "Your guestbook entry was successfully added."; } else { $ret_str = "Your guestbook entry was NOT successfully added."; } // Append success/failure message $gb_str .= "<span class=\"ret\">{$ret_str}</span><br />"; } } // Get entries from database $get_query = "SELECT gbName, gbEmail, gbComment, DATE_FORMAT(gbDateAdded, '%m-%d-%y %H:%i') gbDateAdded\n\t\tFROM guestbook"; $get_rs = mysqli_query($li, $get_query); $gb_str .= "<hr size=\"1\" />"; // While there are still results
if (empty($errors)) { // If everything's OK... // test for unique email address: $q = "SELECT user_id FROM users WHERE email='{$e}' AND user_id != {$id}"; $r = mysqli_query($dbc, $q) or trigger_error("Query: {$q}\n<br />MySQL Error: " . mysqli_error($dbc)); if (mysqli_num_rows($r) == 0) { // Available. // Add the user to the database: $q = "UPDATE users SET first_name = ?, last_name = ?, email = ?, pass = ?, user_level = ? WHERE user_id = ? LIMIT 1"; //prepare the statement $stmt = mysqli_prepare($dbc, $q); //bind the variables mysqli_stmt_bind_param($stmt, 'ssssii', $fn, $ln, $e, SHA1($p), $ul); //execute statement mysqli_stmt_execute($stmt); if (mysqli_stmt_affected_rows($dbc) == 1) { // If it ran OK. // Finish the page: echo ' <section class="fullPanel"> <div class="container-fluid"> <div class="col-sm-2"></div> <div class="col-sm-8"> <p>The user has been edited.</p> </div> <div class="col-sm-2"></div> </div> </section> '; include 'includes/template_bottom.inc.php'; // Include the HTML footer.
function execute($sql) { $stmt = mysqli_prepare(self::$mysqli, $sql); mysqli_stmt_execute($stmt); return mysqli_stmt_affected_rows($stmt); }
$pgroup = $rowEmp['pgroup']; $upload_file = $rowEmp['upload_file']; //$forpc=$rowEmp['pccd']; //$usercode=$rowmaxcode['usercode']; $f_cd = 1; $edcpb = 'E'; $forassembly = NULL; $groupid = NULL; $booked = NULL; $rand_numb = NULL; mysqli_stmt_bind_param($stmt, 'sssssssssssiisssssssssssssssssssssssissisis', $personcd, $officecd, $officer_name, $off_desg, $present_addr1, $present_addr2, $perm_addr1, $perm_addr2, $dateofbirth, $gender, $scale, $basic_pay, $grade_pay, $workingstatus, $email, $resi_no, $mob_no, $qualificationcd, $languagecd, $epic, $acno, $slno, $partno, $poststat, $assembly_temp, $assembly_off, $assembly_perm, $districtcd, $subdivision, $forsubdivision, $bank_acc_no, $bank_cd, $branchcd, $remarks, $pgroup, $upload_file, $usercd, $forpc, $forassembly, $groupid, $booked, $rand_numb, $edcpb); mysqli_stmt_execute($stmt); mysqli_stmt_bind_param($stmt_up, 'is', $f_cd, $personcd); mysqli_stmt_execute($stmt_up); $row_aff += mysqli_stmt_affected_rows($stmt); mysqli_stmt_affected_rows($stmt_up); $rowEmp = NULL; } if (!mysqli_commit($link)) { print "Transaction commit failed\n"; exit; } else { $msg = "<div class='alert-success'>" . $row_aff . " Record(s) transffered successfully</div>"; } mysqli_stmt_close($stmt); mysqli_stmt_close($stmt_up); /* close connection */ mysqli_close($link); $rsEmp = NULL; } }
/** * 按条件删除数据,对应DELETE。 * @return int 数据库语句执行失败为0,成功删除为1,语句执行成功但没有删除为2 */ public function delete() { if ($this->sqlStmt["whereStmt"] === null) { return false; } $rt = false; $sql = "delete from `{$this->tableName}` where " . $this->sqlStmt["whereStmt"]; $this->lastSql = $sql; $stmt = mysqli_prepare($this->conn, $sql); if ($stmt) { if ($this->sqlStmt["bindTypes"] && $this->sqlStmt["bindParams"]) { call_user_func_array([$stmt, "bind_param"], array_merge([$this->sqlStmt["bindTypes"]], $this->arr2Reference($this->sqlStmt["bindParams"]))); } if (mysqli_stmt_execute($stmt)) { if (mysqli_stmt_affected_rows($stmt) > 0) { $rt = 1; } else { $rt = 2; } } else { $this->logError(mysqli_stmt_error($stmt)); } mysqli_stmt_close($stmt); } else { $this->logError(mysqli_error($this->conn)); } $this->initSqlStmt(); $this->degbugLog(); return $rt; }
if (-1 !== ($tmp = mysqli_stmt_affected_rows($stmt))) { printf("[042] Expecting int/-1, got %s/%s\n", gettype($tmp), $tmp); } if ($IS_MYSQLND) { if (false !== ($tmp = mysqli_stmt_store_result($stmt))) { printf("[043] Expecting boolean/false, got %s\\%s\n", gettype($tmp), $tmp); } } else { if (true !== ($tmp = mysqli_stmt_store_result($stmt))) { printf("[043] Libmysql does not care if the previous statement was bogus, expecting boolean/true, got %s\\%s\n", gettype($tmp), $tmp); } } if (0 !== ($tmp = mysqli_stmt_num_rows($stmt))) { printf("[044] Expecting int/0, got %s/%s\n", gettype($tmp), $tmp); } if (-1 !== ($tmp = mysqli_stmt_affected_rows($stmt))) { printf("[045] Expecting int/-1, got %s/%s\n", gettype($tmp), $tmp); } mysqli_stmt_close($stmt); $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, "DROP TABLE IF EXISTS test_mysqli_stmt_affected_rows_table_1") || !mysqli_stmt_execute($stmt)) { printf("[046] [%d] %s\n", mysqli_stmt_errno($stmt), mysqli_stmt_error($stmt)); } mysqli_stmt_close($stmt); if (!is_null($tmp = mysqli_stmt_affected_rows($stmt))) { printf("[047] Expecting NULL, got %s/%s\n", gettype($tmp), $tmp); } mysqli_close($link); print "done!"; $test_table_name = 'test_mysqli_stmt_affected_rows_table_1'; require_once "clean_table.inc";
include '../../../Datos/conexion.php'; $Message = "Numero de indentidad incorrecto"; //Se recupera valor enviado if (isset($_POST['Identidad'])) { $Nid = $_POST['Identidad']; } $sentencia = $conectar->stmt_init(); $sentencia->prepare("CALL SP_OBTENER_INFORMACION_ESTUDIANTE(?, @pcMensajeError)"); if ($Nid != NULL) { try { /* vincular los parámetros para los marcadores */ $sentencia->bind_param("s", $Nid); /* ejecutar la consulta */ $sentencia->execute(); /* vincular las variables de resultados */ if (mysqli_stmt_affected_rows($sentencia)) { $sentencia->bind_result($nombre, $tipo); /* obtener el valor */ $sentencia->fetch(); /* cerrar la sentencia */ $sentencia->close(); /*enviar valores*/ echo $nombre . "*" . $tipo; } else { echo "Número de identidad no existe.*"; } } catch (Exception $e) { echo '<div class="alert alert-info alert-succes"> <a href="#" class="close" data-dismiss="alert">×</a> <strong> Error! intente de nuevo! </strong></div>'; }
$conn = new mysqli(); if ($conn->connect_errno) { die("Failed to connect to MySQL: (" . $conn->connect_error); } //gets the username and password that has been send to this php file $username = $_POST['username']; $password = $_POST['password']; //stores the values into the database with a sql query $sql = mysqli_prepare($conn, "INSERT INTO User (username, password, showname, email, phonenumber) VALUES ( ?, ?, null, null, null)"); mysqli_stmt_bind_param($sql, "ss", $username, $password); mysqli_stmt_execute($sql); if ($sql->error) { error_log("Error: " . $sql->error); } $success = mysqli_stmt_affected_rows($sql); mysqli_stmt_close($sql); if ($success > 0) { echo '{"success":1}'; $statement = "CREATE TABLE " . $username . "Status (username VARCHAR(16) NOT NULL, title VARCHAR(30) DEFAULT NULL, detail VARCHAR(255) NOT NULL, location VARCHAR(30))"; if ($conn->query($statement) === TRUE) { $stmt = "CREATE TABLE " . $username . "Friends (username VARCHAR(16), friendname VARCHAR(16), phone VARCHAR(16), email VARCHAR(30), status INT(5), time TIMESTAMP DEFAULT NULL)"; if ($conn->query($stmt) == TRUE) { $state = "CREATE TABLE " . $username . "Rendezvous (username VARCHAR(16) NOT NULL, showname VARCHAR(16) NOT NULL, frienduser VARCHAR(16) NOT NULL, friendname VARCHAR(16) NOT NULL, title VARCHAR(30) DEFAULT NULL, detail VARCHAR(255) NOT NULL, location VARCHAR(30), time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"; if ($conn->query($state) == TRUE) { } else { echo "Error creating RENDEZVOUS table: " . $conn->error; } } else { echo "Error creating table: " . $conn->error; }
/** * Execute a prepared query statement helper method. * * @param mixed $result_class string which specifies which result class to use * @param mixed $result_wrap_class string which specifies which class to wrap results in * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure * @access private */ function &_execute($result_class = true, $result_wrap_class = false) { if (is_null($this->statement)) { $result =& parent::_execute($result_class, $result_wrap_class); return $result; } $this->db->last_query = $this->query; $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values)); if ($this->db->getOption('disable_query')) { $result = $this->is_manip ? 0 : null; return $result; } $connection = $this->db->getConnection(); if (PEAR::isError($connection)) { return $connection; } if (!is_object($this->statement)) { $query = 'EXECUTE ' . $this->statement; } if (!empty($this->positions)) { $parameters = array(0 => $this->statement, 1 => ''); $lobs = array(); $i = 0; foreach ($this->positions as $parameter) { if (!array_key_exists($parameter, $this->values)) { return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, 'Unable to bind to missing placeholder: ' . $parameter, __FUNCTION__); } $value = $this->values[$parameter]; $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null; if (!is_object($this->statement)) { if (is_resource($value) || $type == 'clob' || $type == 'blob') { if (!is_resource($value) && preg_match('/^(\\w+:\\/\\/)(.*)$/', $value, $match)) { if ($match[1] == 'file://') { $value = $match[2]; } $value = @fopen($value, 'r'); $close = true; } if (is_resource($value)) { $data = ''; while (!@feof($value)) { $data .= @fread($value, $this->db->options['lob_buffer_length']); } if ($close) { @fclose($value); } $value = $data; } } $quoted = $this->db->quote($value, $type); if (PEAR::isError($quoted)) { return $quoted; } $param_query = 'SET @' . $parameter . ' = ' . $quoted; $result = $this->db->_doQuery($param_query, true, $connection); if (PEAR::isError($result)) { return $result; } } else { if (is_resource($value) || $type == 'clob' || $type == 'blob') { $parameters[] = null; $parameters[1] .= 'b'; $lobs[$i] = $parameter; } else { $parameters[] = $this->db->quote($value, $type, false); $parameters[1] .= $this->db->datatype->mapPrepareDatatype($type); } ++$i; } } if (!is_object($this->statement)) { $query .= ' USING @' . implode(', @', array_values($this->positions)); } else { $result = @call_user_func_array('mysqli_stmt_bind_param', $parameters); if ($result === false) { $err =& $this->db->raiseError(null, null, null, 'Unable to bind parameters', __FUNCTION__); return $err; } foreach ($lobs as $i => $parameter) { $value = $this->values[$parameter]; $close = false; if (!is_resource($value)) { $close = true; if (preg_match('/^(\\w+:\\/\\/)(.*)$/', $value, $match)) { if ($match[1] == 'file://') { $value = $match[2]; } $value = @fopen($value, 'r'); } else { $fp = @tmpfile(); @fwrite($fp, $value); @rewind($fp); $value = $fp; } } while (!@feof($value)) { $data = @fread($value, $this->db->options['lob_buffer_length']); @mysqli_stmt_send_long_data($this->statement, $i, $data); } if ($close) { @fclose($value); } } } } if (!is_object($this->statement)) { $result = $this->db->_doQuery($query, $this->is_manip, $connection); if (PEAR::isError($result)) { return $result; } if ($this->is_manip) { $affected_rows = $this->db->_affectedRows($connection, $result); return $affected_rows; } $result =& $this->db->_wrapResult($result, $this->result_types, $result_class, $result_wrap_class, $this->limit, $this->offset); } else { if (!@mysqli_stmt_execute($this->statement)) { $err =& $this->db->raiseError(null, null, null, 'Unable to execute statement', __FUNCTION__); return $err; } if ($this->is_manip) { $affected_rows = @mysqli_stmt_affected_rows($this->statement); return $affected_rows; } if ($this->db->options['result_buffering']) { @mysqli_stmt_store_result($this->statement); } $result =& $this->db->_wrapResult($this->statement, $this->result_types, $result_class, $result_wrap_class, $this->limit, $this->offset); } $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result)); return $result; }
/* now we should try mysqli_stmt_reset() */ $stmt = mysqli_prepare($link, "SELECT * FROM test_057_table_1"); var_dump(mysqli_stmt_execute($stmt)); var_dump(mysqli_stmt_reset($stmt)); var_dump($stmt = mysqli_prepare($link, "SELECT * FROM test_057_table_1")); if ($stmt->affected_rows !== 0) { printf("[001] Expecting 0, got %d\n", $stmt->affected_rows); } var_dump(mysqli_stmt_execute($stmt)); var_dump($stmt = @mysqli_prepare($link, "SELECT * FROM test_057_table_1"), mysqli_error($link)); var_dump(mysqli_stmt_reset($stmt)); $stmt = mysqli_prepare($link, "SELECT * FROM test_057_table_1"); mysqli_stmt_execute($stmt); $result1 = mysqli_stmt_result_metadata($stmt); mysqli_stmt_store_result($stmt); printf("Rows: %d\n", mysqli_stmt_affected_rows($stmt)); /* this should show an error, cause results are not buffered */ if ($result = mysqli_query($link, "SELECT * FROM test_057_table_1")) { $row = mysqli_fetch_row($result); mysqli_free_result($result); } var_dump($row); mysqli_free_result($result1); mysqli_stmt_close($stmt); mysqli_close($link); echo "done!"; require_once "connect.inc"; if (!($link = my_mysqli_connect($host, $user, $passwd, $db, $port, $socket))) { printf("[c001] [%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()); } if (!mysqli_query($link, "DROP TABLE IF EXISTS test_057_table_1")) {
$stmt = mysqli_prepare($dbc, $q); mysqli_stmt_bind_param($stmt, 'sidss', $type, $id, $price, $start_date, $end_date); // Count the number of affected rows: $affected = 0; // Loop through each provided value: foreach ($_POST['sale_price'] as $sku => $price) { // Validate the price and start date: if (filter_var($price, FILTER_VALIDATE_FLOAT) && $price > 0 && !empty($_POST['start_date'][$sku])) { // Parse the SKU: list($type, $id) = parse_sku($sku); // Get the dates: $start_date = $_POST['start_date'][$sku]; $end_date = empty($_POST['end_date'][$sku]) ? NULL : $_POST['end_date'][$sku]; // Execute the query: mysqli_stmt_execute($stmt); $affected += mysqli_stmt_affected_rows($stmt); } // End of price/date validation IF. } // End of FOREACH loop. // Indicate the results: echo "<h4>{$affected} Sales Were Created!</h4>"; } // $_POST variables aren't set. } // End of the submission IF. ?> <h3>Create Sales</h3> <p>To mark an item as being on sale, indicate the sale price, the date the sale starts, and the date the sale ends. You may leave the end date blank, thereby creating an open-ended sale. Only the currently stocked products are listed below!</p> <form action="create_sales.php" method="post" accept-charset="utf-8">
} else { // If it did not run OK. trigger_error('Your password could not be changed due to a system error. We apologize for any inconvenience.'); } */ // Bonus material! // Referenced in Chapter 12: $token = openssl_random_pseudo_bytes(32); $token = bin2hex($token); // Store the token in the database: $q = 'REPLACE INTO access_tokens (user_id, token, date_expires) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 15 MINUTE))'; $stmt = mysqli_prepare($dbc, $q); mysqli_stmt_bind_param($stmt, 'is', $uid, $token); mysqli_stmt_execute($stmt); if (mysqli_stmt_affected_rows($stmt) > 0) { $url = 'https://' . BASE_URL . 'reset.php?t=' . $token; $body = "This email is in response to a forgotten password reset request at 'Knowledge is Power'. If you did make this request, click the following link to be able to access your account:\n{$url}\nFor security purposes, you have 15 minutes to do this. If you do not click this link within 15 minutes, you'll need to request a password reset again.\nIf you have _not_ forgotten your password, you can safely ignore this message and you will still be able to login with your existing password. "; mail($email, 'Password Reset at Knowledge is Power', $body, 'FROM: ' . CONTACT_EMAIL); echo '<h1>Reset Your Password</h1><p>You will receive an access code via email. Click the link in that email to gain access to the site. Once you have done that, you may then change your password.</p>'; include './includes/footer.html'; exit; // Stop the script. } else { // If it did not run OK. trigger_error('Your password could not be changed due to a system error. We apologize for any inconvenience.'); } } // End of empty($pass_errors) IF. } // End of the main Submit conditional.
public function executeNonQuery($sql, $argv = NULL) { //Logger::trace("MysqlDao.executeNonQuery executed", LOG_LEVEL_NOTICE); $affected = 0; // 校验参数有效性 $lowstr = strtolower($sql); if (strtolower(substr($lowstr, 0, 6)) === "select") { echo "Invalid query SQL statement."; } //echo $sql; // 创建数据库连接(如果需要) $connected = $this->connected(); $conn = $connected ? $this->conn : $this->connect(FALSE); // 将默认字符集设置为utf8 mysqli_query($conn, "set names 'utf8'"); mysqli_query($conn, "set character set 'utf8'"); // 执行SQL语句 $stmt = mysqli_prepare($conn, $sql); if (mysqli_errno($conn)) { $errno = mysqli_errno($conn); $error = "MYSQL ERROR #" . $errno . " : " . mysqli_error($conn); echo $error; } // 根据参数的个数动态生成参数绑定语句 if (isset($argv) && count($argv) > 0) { $bind_param_cmd = "mysqli_stmt_bind_param(\$stmt, "; $paramstr = ""; $bindstr = ""; $holdstr = ""; $i = 0; foreach ($argv as $arg) { $paramstr .= "\$invar{$i}, "; $bindstr .= "\$invar{$i} = \$argv[{$i}]; "; $holdstr .= "s"; $i++; } $bind_param_cmd = "mysqli_stmt_bind_param(\$stmt, \"{$holdstr}\", " . substr($paramstr, 0, strlen($paramstr) - 2) . "); "; $bind_param_cmd .= $bindstr; eval($bind_param_cmd); //将字符串中的变量代入 } // 执行SQL语句 mysqli_stmt_execute($stmt); if (mysqli_stmt_errno($stmt)) { $errno = mysqli_stmt_errno($stmt); $error = "MYSQL ERROR #" . $errno . " : " . mysqli_stmt_error($stmt); echo $error; } $this->insert_id = mysqli_stmt_insert_id($stmt); //数据库操作数据id //echo $this->insert_id; $affected = mysqli_stmt_affected_rows($stmt); mysqli_stmt_close($stmt); // 关闭数据库连接(如果需要) if (!$connected) { $this->disconnect($conn); } return $affected; }
// Validate the artist... if (isset($_POST['artist']) && filter_var($_POST['artist'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $a = $_POST['artist']; } else { // No artist selected. $errors[] = 'Please select the print\'s artist!'; } if (empty($errors)) { // If everything's OK. // Add the print to the database: $q = "INSERT INTO prints (artist_id, print_name, price, size, description, image_name) VALUES (?, ?, ?, ?, ?, ?)"; $stmt = mysqli_prepare($dbc, $q); mysqli_stmt_bind_param($stmt, 'isdsss', $a, $pn, $p, $s, $d, $i); mysqli_stmt_execute($stmt); // Check the results... if (mysqli_stmt_affected_rows($stmt) == 1) { // Print a message: echo '<p>The print has been added.</p>'; // Rename the image: $id = mysqli_stmt_insert_id($stmt); // Get the print ID. rename($temp, "../uploads/{$id}"); // Clear $_POST: $_POST = array(); } else { // Error! echo '<p style="font-weight: bold; color: #C00">Your submission could not be processed due to a system error.</p>'; } mysqli_stmt_close($stmt); } // End of $errors IF.