本文整理汇总了PHP中sqlsrv_rows_affected函数的典型用法代码示例。如果您正苦于以下问题:PHP sqlsrv_rows_affected函数的具体用法?PHP sqlsrv_rows_affected怎么用?PHP sqlsrv_rows_affected使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sqlsrv_rows_affected函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: queryUpdate
/**
* Ejecuta una query update.
*
* @param resource $conn
* @param string $tabla
* La tabla a la que queremos hacerle la query.
* @param array $set
* Los campos que irán en la cláusula <b><i>SET</i></b>. <br>Donde
* <b><i>key</i></b> el el nombre del campo y <b><i>value</i></b> es
* el valor a comparar.
* @param aray $where
* Nombre de los campos que queremos mostrar en la cláusula
* <b><i>WHERE</i></b>.
* @param string $SQLserverName
* @return mixed array si hay un error. String columnas afectadas.
*/
function queryUpdate($conn, $tabla, $set, $where, $SQLserverName)
{
$updateString = "UPDATE {$tabla} SET ";
$primerElemento = true;
foreach ($set as $key => $value) {
if (strlen($value) == 0) {
unset($set[$key]);
continue;
}
if ($primerElemento) {
$updateString .= " {$key} = ?";
$primerElemento = false;
} else {
$updateString .= ", {$key} = ?";
}
}
$whereString = " WHERE ";
$primerElemento = true;
foreach ($where as $key => $value) {
if ($primerElemento) {
$whereString .= " ({$key} = ?)";
$primerElemento = false;
} else {
$whereString .= " and ({$key} = ?)";
}
}
$sql = $updateString . $whereString;
$parametros = array_merge($set, $where);
$parametros = array_values($parametros);
// Ejecutar la query
//////////////////////////////////////////////////////
if ($farmacia == FARMACIA_DEBUG or strlen(FARMACIA_DEBUG) == 0) {
if (DEBUG & DEBUG_QUERY) {
$mensaje = "--[" . date("c") . "] Farmacia: {$farmacia} \n";
$mensaje .= "--Query hecha en el fichero: " . __FILE__ . ", en la línea: " . __LINE__ . "\n";
error_log($mensaje . verQuery($sql, $parametros) . "\r\n", 3, DIRECTORIO_LOG . __FUNCTION__ . "_" . date("YmdH") . ".log");
}
}
$stmt = sqlsrv_query($conn, $sql, $parametros);
if ($stmt === false) {
if (($errors = sqlsrv_errors()) != null) {
$Merror = $errors[0]["message"];
/* Guardamos en un fichero el error y la query que lo ha generado para poder procesarlo después.
* Sólo en este caso no nos fijamos en el valor de la constante DEBUG ya que nos interesa guardarlo.*/
$mensaje = "--[" . date("c") . "] farmacia: {$farmacia} mensaje: {$Merror} \n";
$mensaje .= "--Error en el fichero: " . __FILE__ . ", en la línea: " . __LINE__;
error_log($mensaje . verQuery($sql, $parametros) . "\r\n", 3, DIRECTORIO_LOG . $tabla . "_" . $SQLserverName . "_" . date("YmdH") . ".log");
return $errors;
}
}
// Desplegar la información del resultado
//////////////////////////////////////////////////////
return sqlsrv_rows_affected($stmt);
}
示例2: BatchUpdate
function BatchUpdate($itemNameQuery, $expenses, $durability, $useInstructions)
{
// Alterar apenas campos de usuário aqui (começados com U_ ), é proibido alterar campos do SAP B1
$query = "UPDATE OITM SET U_Expenses = " . $expenses . ",U_Durability = " . $durability . ", U_UseInstructions = '" . $useInstructions . "' WHERE ItemName LIKE '%" . $itemNameQuery . "%'";
$result = sqlsrv_query($this->sqlserverConnection, $query);
if ($result) {
return sqlsrv_rows_affected($result);
}
if (!$result && $this->showErrors) {
print_r(sqlsrv_errors());
echo '<br/>';
}
return null;
}
示例3: queryInsert
/**
* Ejecuta una query insert.
*
* @param resource $conn
* @param string $tabla
* La tabla a la que queremos hacerle el insert.
* @param array $parametros
* Los campos que se van a insertar. <br>Donde
* <b><i>key</i></b> el el nombre del campo y <b><i>value</i></b> es
* el valor del mismo.
* @param string $SQLserverName
* @return mixed Array si hay errores de SQL.
* Int con el número de filas afectadas (0..n).
*/
function queryInsert($conn, $tabla, $parametros, $SQLserverName)
{
global $farmacia;
$respuestaError = new respuestaError();
if (isset($parametros["farmacia"])) {
$farmacia = $parametros["farmacia"];
}
$insertString = "INSERT INTO {$tabla} (";
$values = "VALUES (";
$primerElemento = true;
foreach ($parametros as $key => $value) {
if ($primerElemento) {
$insertString .= "{$key}";
$values .= "?";
$primerElemento = false;
} else {
$insertString .= ", {$key}";
$values .= ", ?";
}
}
$insertString .= ") ";
$values .= ")";
$sql = $insertString . $values;
$parametros = array_values($parametros);
// Ejecutar la query
//////////////////////////////////////////////////////
if ($farmacia == FARMACIA_DEBUG or strlen(FARMACIA_DEBUG) == 0) {
if (DEBUG & DEBUG_QUERY) {
$mensaje = "--[" . date("c") . "] Farmacia: {$farmacia} \n";
$mensaje .= "--Query hecha en el fichero: " . __FILE__ . ", en la línea: " . __LINE__ . "\n";
error_log($mensaje . verQuery($sql, $parametros) . "\r\n", 3, DIRECTORIO_LOG . __FUNCTION__ . "_" . date("YmdH") . ".log");
}
}
$stmt = sqlsrv_query($conn, $sql, $parametros);
if ($stmt === false) {
if (($errors = sqlsrv_errors()) != null) {
$Merror = $errors[0]["message"];
/* Guardamos en un fichero el error y la query que lo ha generado para poder procesarlo después.
* Sólo en este caso no filtramos el valor de la constante DEBUG ya que en cualquier caso nos interesa guardar el error.*/
$mensaje = "--[" . date("c") . "] farmacia: {$farmacia} mensaje: {$Merror} \n";
$mensaje .= "--Error en el fichero: " . __FILE__ . ", en la línea: " . __LINE__ . "\n";
error_log($mensaje . verQuery($sql, $parametros) . "\r\n", 3, DIRECTORIO_LOG . $tabla . "_" . $SQLserverName . "_" . date("YmdH") . ".log");
return $errors;
}
}
// Desplegar la información del resultado
//////////////////////////////////////////////////////
return sqlsrv_rows_affected($stmt);
}
示例4: execute
public function execute($sql, array $data = null)
{
$this->connect();
if (!is_array($data)) {
$data = array();
}
$temp = sqlsrv_query($this->lnk, $sql, $data);
if (!$temp) {
throw new DatabaseException('Could not execute query : ' . json_encode(sqlsrv_errors()) . ' <' . $sql . '>');
}
if (preg_match('@^\\s*(INSERT|REPLACE)\\s+INTO@i', $sql)) {
$this->iid = sqlsrv_query($this->lnk, 'SELECT SCOPE_IDENTITY()');
if ($this->iid) {
$this->iid = sqlsrv_fetch_array($this->iid, \SQLSRV_FETCH_NUMERIC);
$this->iid = $this->iid[0];
}
$this->aff = sqlsrv_rows_affected($temp);
}
return $temp;
}
示例5: rowCount
/**
* Returns the number of rows affected by the execution of the
* last INSERT, DELETE, or UPDATE statement executed by this
* statement object.
*
* @return int The number of rows affected.
* @throws Zend_Db_Statement_Exception
*/
public function rowCount()
{
if (!$this->_stmt) {
return false;
}
if (!$this->_executed) {
return 0;
}
$num_rows = sqlsrv_rows_affected($this->_stmt);
// Strict check is necessary; 0 is a valid return value
if ($num_rows === false) {
require_once 'include/Zend/Db/Statement/Sqlsrv/Exception.php';
throw new Zend_Db_Statement_Sqlsrv_Exception(sqlsrv_errors());
}
return $num_rows;
}
示例6: setNbRow
/**
* (non-PHPdoc)
* @see classes/connectionengine/Result_STH#setNbRow()
*/
protected function setNbRow()
{
$this->nbRow = sqlsrv_rows_affected($this->result);
if ($this->nbRow === false) {
throw new ConnectionengineException('Error in calling sqlsrv_rows_affected: ' . $this->query, __FILE__, __LINE__, sqlsrv_errors());
}
if ($this->nbRow == -1) {
$this->nbRow = 0;
}
}
示例7: isAffected
function isAffected($stmt)
{
$result = sqlsrv_rows_affected($stmt);
if ($result > 0) {
return $result;
} else {
return 0;
}
}
示例8: affected_rows
/**
* Affected Rows
*
* @return int
*/
public function affected_rows()
{
return sqlsrv_rows_affected($this->result_id);
}
示例9: query
public function query($sql, $errorLevel = E_USER_ERROR)
{
if (isset($_REQUEST['previewwrite']) && in_array(strtolower(substr($sql, 0, strpos($sql, ' '))), array('insert', 'update', 'delete', 'replace'))) {
Debug::message("Will execute: {$sql}");
return;
}
if (isset($_REQUEST['showqueries'])) {
$starttime = microtime(true);
}
$error = '';
if ($this->mssql) {
$handle = mssql_query($sql, $this->dbConn);
$error = mssql_get_last_message();
} else {
$handle = sqlsrv_query($this->dbConn, $sql);
if ($handle) {
$this->lastAffectedRows = sqlsrv_rows_affected($handle);
}
if (function_exists('sqlsrv_errors')) {
$errInfo = sqlsrv_errors();
if ($errInfo) {
foreach ($errInfo as $info) {
$error .= implode(', ', array($info['SQLSTATE'], $info['code'], $info['message']));
}
}
}
}
if (isset($_REQUEST['showqueries'])) {
$endtime = round(microtime(true) - $starttime, 4);
Debug::message("\n{$sql}\n{$endtime}ms\n", false);
}
if (!$handle && $errorLevel) {
$this->databaseError("Couldn't run query ({$error}): {$sql}", $errorLevel);
}
return new MSSQLQuery($this, $handle, $this->mssql);
}
示例10: insertSelect
/**
* INSERT SELECT wrapper
* $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
* Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
* $conds may be "*" to copy the whole table
* srcTable may be an array of tables.
*/
function insertSelect($destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseMssql::insertSelect', $insertOptions = array(), $selectOptions = array())
{
$ret = parent::insertSelect($destTable, $srcTable, $varMap, $conds, $fname, $insertOptions, $selectOptions);
if ($ret === false) {
throw new DBQueryError($this, $this->getErrors(), $this->lastErrno(), '', $fname);
} elseif ($ret != NULL) {
// remember number of rows affected
$this->mAffectedRows = sqlsrv_rows_affected($ret);
return $ret;
}
return NULL;
}
示例11: affectedRows
/**
* Retrieve number of affected rows for last query
*
* @return int
*/
protected function affectedRows()
{
return sqlsrv_rows_affected($this->result);
}
示例12: query
//.........这里部分代码省略.........
// strip_invalid_text_from_query() can perform queries, so we need
// to flush again, just to make sure everything is clear.
$this->flush();
if ($stripped_query !== $query) {
$this->insert_id = 0;
return false;
}
}
$this->check_current_query = true;
// Keep track of the last query for debug..
$this->last_query = $query;
$this->_do_query($query);
// MySQL server has gone away, try to reconnect
/*
$mysql_errno = 0;
if ( ! empty( $this->dbh ) ) {
if ( $this->use_mysqli ) {
$mysql_errno = mysqli_errno( $this->dbh );
} else {
$mysql_errno = mysql_errno( $this->dbh );
}
}
if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
if ( $this->check_connection() ) {
$this->_do_query( $query );
} else {
$this->insert_id = 0;
return false;
}
}
*/
// If there is an error, first attempt to translate
$errors = sqlsrv_errors();
if (!empty($errors) && is_array($errors)) {
switch ($errors[0]['code']) {
case 102:
case 145:
case 156:
case 195:
case 207:
case 241:
case 261:
case 321:
case 1018:
case 8120:
case 8127:
if (getenv('ProjectNamiLogTranslate')) {
$begintransmsg = date("Y-m-d H:i:s") . " -- Begin translation attempt: {$query} \n";
error_log($begintransmsg, 3, 'D:\\home\\LogFiles\\translate.log');
}
$sqltranslate = new SQL_Translations(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$query = $sqltranslate->translate($query);
if (getenv('ProjectNamiLogTranslate')) {
$endtransmsg = date("Y-m-d H:i:s") . " -- Translation result: {$query} \n";
error_log($endtransmsg, 3, 'D:\\home\\LogFiles\\translate.log');
}
$this->last_query = $query;
$this->_do_query($query);
// If there is an error then take note of it..
$errors = sqlsrv_errors();
}
}
if (!empty($errors) && is_array($errors)) {
$this->last_error = $errors[0]['message'];
// Clear insert_id on a subsequent failed insert.
if ($this->insert_id && preg_match('/^\\s*(insert|replace)\\s/i', $query)) {
$this->insert_id = 0;
}
$this->print_error();
return false;
}
if (preg_match('/^\\s*(create|alter|truncate|drop)\\s/i', $query)) {
$return_val = $this->result;
} elseif (preg_match('/^\\s*(insert|delete|update|replace)\\s/i', $query) && $this->query_statement_resource != false) {
$this->rows_affected = sqlsrv_rows_affected($this->query_statement_resource);
// Take note of the insert_id
if (preg_match('/^\\s*(insert|replace)\\s/i', $query)) {
$this->insert_id = sqlsrv_query($this->dbh, 'SELECT isnull(scope_identity(), 0)');
$row = sqlsrv_fetch_array($this->insert_id);
$this->insert_id = $row[0];
}
// Return number of rows affected
$return_val = $this->rows_affected;
} else {
$num_rows = 0;
while ($row = @sqlsrv_fetch_object($this->query_statement_resource)) {
$this->last_result[$num_rows] = $row;
$num_rows++;
}
// Log number of rows the query returned
// and return number of rows selected
$this->num_rows = $num_rows;
$return_val = $num_rows;
}
if (isset($this->last_result[0]) && is_object($this->last_result[0]) && isset($this->last_result[0]->found_rows)) {
$this->last_query_total_rows = $this->last_result[0]->found_rows;
}
return $return_val;
}
示例13: query
public function query($type, $sql, $as_object = FALSE, array $params = NULL)
{
// Make sure the database is connected
$this->_connection or $this->connect();
if (!empty($this->_config['profiling'])) {
// Benchmark this query for the current instance
$benchmark = Profiler::start("Database ({$this->_instance})", $sql);
}
// Detect type Database::INSERT and ensure last id is captured
if ($type === Database::INSERT) {
// We need to do some magic here to get the insert ID
// this is a glorious hack!
$sql_statement = (string) $sql;
// Locate VALUES
$values = strpos($sql, 'VALUES');
// Insert the lastInsertId logic
$sql = substr($sql_statement, 0, $values) . 'output inserted.identitycol AS lastInsertId ' . substr($sql_statement, $values);
}
// Execute the query
if (($result = sqlsrv_query($this->_connection, $sql, $params, array('Scrollable' => SQLSRV_CURSOR_KEYSET))) === FALSE) {
// If something went wrong
if (isset($benchmark)) {
// This benchmark is worthless
Profiler::delete($benchmark);
}
// Get the errors
$error = sqlsrv_errors(SQLSRV_ERR_ERRORS);
// Throw an exception
throw new Database_Sqlsrv_Exception(':error [ :query ]', array(':error' => $error[0]['message'], ':query' => $sql), $error[0]['code']);
}
if (isset($benchmark)) {
Profiler::stop($benchmark);
}
// Set the last query
$this->last_query = $sql;
if ($type === Database::SELECT) {
// Return an iterator of results
return new Database_Sqlsrv_Result($result, $sql, $as_object);
} elseif ($type === Database::INSERT) {
// Get the last insert id
if (($insert_id = sqlsrv_fetch_array($result)) === FALSE) {
// Get the errors
$error = sqlsrv_errors(SQLSRV_ERR_ERRORS);
// Throw an exception
throw new Database_Sqlsrv_Exception(':error [ :query ]', array(':error' => 'Unable to get the last inserted row ID from driver', ':query' => $sql), $error[0]['code']);
}
return array($insert_id['lastInsertId'], sqlsrv_rows_affected($result));
} else {
// Return the number of rows affected
return sqlsrv_rows_affected($result);
}
}
示例14: execute
public function execute($bind_params = false)
{
$ret_val = false;
$arg_list = func_get_args();
$lazy = isset($arg_list[1]) && $arg_list[1] ? true : false;
//----------------------------------------------
// Prepare SQL Statement
//----------------------------------------------
$prepare_status = $this->_prepare($this->curr_query, $bind_params, $lazy);
if (!$prepare_status) {
if ($this->check_and_print_error()) {
return false;
}
$this->print_error('Query prepare failed.');
return false;
}
if (!$this->stmt) {
return false;
}
//----------------------------------------------
// Execute Query
//----------------------------------------------
$exec_status = @sqlsrv_execute($this->stmt);
if (!$exec_status) {
if ($this->check_and_print_error()) {
return false;
}
$this->print_error('Query execution failed.');
return false;
}
//----------------------------------------------
// Create Data Result Object if Necessary
//----------------------------------------------
if ($this->stmt && gettype($this->stmt) != 'boolean') {
//----------------------------------------------
// Affected Rows
//----------------------------------------------
$this->affected_rows = sqlsrv_rows_affected($this->stmt);
$ret_val = $this->affected_rows;
//----------------------------------------------
// Create Data Result Object
//----------------------------------------------
$has_rows = sqlsrv_has_rows($this->stmt);
$this->data_result = new data_result($this->stmt, $this->data_src);
//----------------------------------------------
// Last Insert ID
//----------------------------------------------
$this->last_id = null;
}
//----------------------------------------------
// Return Data Result Object if it exists
//----------------------------------------------
if ($this->data_result) {
$this->num_rows = $this->data_result->num_rows();
$this->num_fields = $this->data_result->num_fields();
$ret_val = $this->data_result;
}
//----------------------------------------------
// Check for Errors
//----------------------------------------------
if ($this->check_and_print_error()) {
return false;
}
return $ret_val;
}
示例15: doQuery
/**
* @param string $sql
* @return bool|MssqlResult
* @throws DBUnexpectedError
*/
protected function doQuery($sql)
{
global $wgDebugDumpSql;
if ($wgDebugDumpSql) {
wfDebug("SQL: [{$sql}]\n");
}
$this->offset = 0;
// several extensions seem to think that all databases support limits
// via LIMIT N after the WHERE clause well, MSSQL uses SELECT TOP N,
// so to catch any of those extensions we'll do a quick check for a
// LIMIT clause and pass $sql through $this->LimitToTopN() which parses
// the limit clause and passes the result to $this->limitResult();
if (preg_match('/\\bLIMIT\\s*/i', $sql)) {
// massage LIMIT -> TopN
$sql = $this->LimitToTopN($sql);
}
// MSSQL doesn't have EXTRACT(epoch FROM XXX)
if (preg_match('#\\bEXTRACT\\s*?\\(\\s*?EPOCH\\s+FROM\\b#i', $sql, $matches)) {
// This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
$sql = str_replace($matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql);
}
// perform query
// SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
// needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
// has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
// strings make php throw a fatal error "Severe error translating Unicode"
if ($this->mScrollableCursor) {
$scrollArr = array('Scrollable' => SQLSRV_CURSOR_STATIC);
} else {
$scrollArr = array();
}
if ($this->mPrepareStatements) {
// we do prepare + execute so we can get its field metadata for later usage if desired
$stmt = sqlsrv_prepare($this->mConn, $sql, array(), $scrollArr);
$success = sqlsrv_execute($stmt);
} else {
$stmt = sqlsrv_query($this->mConn, $sql, array(), $scrollArr);
$success = (bool) $stmt;
}
if ($this->mIgnoreDupKeyErrors) {
// ignore duplicate key errors, but nothing else
// this emulates INSERT IGNORE in MySQL
if ($success === false) {
$errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
$success = true;
foreach ($errors as $err) {
if ($err['SQLSTATE'] == '23000' && $err['code'] == '2601') {
continue;
// duplicate key error
} elseif ($err['SQLSTATE'] == '01000' && $err['code'] == '3621') {
continue;
// generic "the statement has been terminated" error
}
$success = false;
// getting here means we got an error we weren't expecting
break;
}
if ($success) {
$this->mAffectedRows = 0;
return true;
}
}
}
if ($success === false) {
return false;
}
// remember number of rows affected
$this->mAffectedRows = sqlsrv_rows_affected($stmt);
return $stmt;
}