Execute a SQL query

@param string SQL query to execute
@param mixed  Values to be inserted in query

@return number  Query handle identifier
327750
public function query()
    {
        $params = func_get_args();
        $query = array_shift($params);

        // Support one argument of type array, instead of n arguments
        if (count($params) == 1 && is_array($params[0])) {
            $params = $params[0];
        }

        return $this->_query($query, 0, 0, $params);
    }
1273079
public function execute($sql, $params = null)
    {
        $stmt = $this->_pdo->prepare($sql);

        if (is_array($params)) {
            foreach ($params as $token => $value) {
                $stmt->bindValue($token, $value);
            }
        }

        try {
            $stmt->execute();
        } catch (PDOException $exception) {
            $this->_database->error('execute', $exception);
        }

        return $stmt;
    }
528625
public function executeRaw($sql) {
        if (!is_string($sql)) throw new IllegalTypeException('Illegal type of parameter $sql: '.gettype($sql));
        if (!$this->isConnected())
            $this->connect();

        // execute statement
        $result = null;
        try {
            $result = pg_query($this->hConnection, $sql);         // wraps multi-statement queries in a transaction
            !$result && trigger_error(pg_last_error($this->hConnection), E_USER_ERROR);
        }
        catch (\Exception $ex) {
            if (!$ex instanceof IRosasurferException)
                $ex = new DatabaseException($ex->getMessage(), $ex->getCode(), $ex);
            throw $ex->addMessage('Database: '.$this->getConnectionDescription().NL.'SQL: "'.$sql.'"');
        }

        $status_string = pg_result_status($result, PGSQL_STATUS_STRING);

        // reset last_insert_id on INSERTs, afterwards it's resolved on request as it requires an extra SQL query
        if (strStartsWithI($status_string, 'INSERT '))
            $this->lastInsertId = null;

        // track last_affected_rows
        $pattern = '/^(INSERT|UPDATE|DELETE)\b/i';
        if (preg_match($pattern, $status_string))
            $this->lastAffectedRows = pg_affected_rows($result);

        return $result;

    }
347974
protected function _execute($sql, $bind)
    {
        if (!isset($this->_prepared[$sql])) {
            if (count($this->_prepared) > 8) {
                array_shift($this->_prepared);
            }
            $this->_prepared[$sql] = @$this->_getPdo()->prepare($sql);
        }
        $statement = $this->_prepared[$sql];

        foreach ($bind as $parameter => $value) {
            if (is_string($value)) {
                $type = \PDO::PARAM_STR;
            } elseif (is_int($value)) {
                $type = \PDO::PARAM_INT;
            } elseif (is_bool($value)) {
                $type = \PDO::PARAM_BOOL;
            } elseif ($value === null) {
                $type = \PDO::PARAM_NULL;
            } elseif (is_float($value)) {
                $type = \PDO::PARAM_STR;
            } elseif (is_array($value) || $value instanceof \JsonSerializable) {
                $type = \PDO::PARAM_STR;
                $value = json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            } else {
                throw new NotSupportedException(['The `:1` type of `:2` parameter is not support', $parameter, gettype($value)]);
            }

            if (is_int($parameter)) {
                $statement->bindValue($parameter + 1, $value, $type);
            } else {
                if ($parameter[0] === ':') {
                    throw new InvalidValueException(['Bind does not require started with `:` for `:parameter` parameter', 'parameter' => $parameter]);
                }

                $statement->bindValue(':' . $parameter, $value, $type);
            }
        }

        @$statement->execute();

        return $statement;
    }
248989
public function execute($sql, array $parameters = [])
    {
        $sth = $this->prepare($sql);
        $sth->execute($parameters);
        return $sth;
    }
1098028
protected function execute($sql, $bindings = array())
		{
			$bindings = (array) $bindings;

			// Since expressions are injected into the query as strings, we need to
			// remove them from the array of bindings. After we have removed them,
			// we'll reset the array so there aren't gaps in the keys.
			$bindings = array_values(array_filter($bindings, function($binding) {
				return ! $binding instanceof Expression;
			}));

			$sql = $this->grammar()->shortcut($sql, $bindings);

			$statement = $this->pdo->prepare($sql);

			// Every query is timed so that we can log the executinon time along
			// with the query SQL and array of bindings. This should be make it
			// convenient for the developer to profile performance.
			$time = microtime(true);

			$result = $statement->execute($bindings);

			$time = number_format((microtime(true) - $time) * 1000, 2);

			// Once we have execute the query, we log the SQL, bindings, and
			// execution time in a static array that is accessed by all of
			// the connections used by the application.
			$this->log($sql, $bindings, $time);

			return array($statement, $result);
		}
156077
public function exec($sql_string)
	{
		$this->sql_string = $sql_string;
		$query = sasql_query( $this->connection, $this->sql_string );
		if ( $query ) {
			return new SQLAnywhereQuery( $query, $this->connection );
		} else {
			throw new Exception("SQL String Problem :: " . sasql_error( $this->connection ), 110);		
		}
		return 0;
	}
39325
public void execute(String query, Object... params) throws SQLException {
        createPreparedStatement(query, 0, params).execute();
    }
33112
public function execute()
	{
		$this->connect();

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		// Execute the query.
		$this->executed = false;

		if ($this->prepared instanceof \mysqli_stmt)
		{
			// Bind the variables:
			if ($this->sql instanceof PreparableInterface)
			{
				$bounded =& $this->sql->getBounded();

				if (\count($bounded))
				{
					$params     = array();
					$typeString = '';

					foreach ($bounded as $key => $obj)
					{
						// Add the type to the type string
						$typeString .= $obj->dataType;

						// And add the value as an additional param
						$params[] = $obj->value;
					}

					// Make everything references for call_user_func_array()
					$bindParams   = array();
					$bindParams[] = &$typeString;

					for ($i = 0, $iMax = \count($params); $i < $iMax; $i++)
					{
						$bindParams[] = &$params[$i];
					}

					\call_user_func_array(array($this->prepared, 'bind_param'), $bindParams);
				}
			}

			$this->executed = $this->prepared->execute();
			$this->cursor   = $this->prepared->get_result();

			// If the query was successful and we did not get a cursor, then set this to true (mimics mysql_query() return)
			if ($this->executed && !$this->cursor)
			{
				$this->cursor = true;
			}
		}

		// If an error occurred handle it.
		if (!$this->executed)
		{
			$this->errorNum = (int) $this->connection->errno;
			$this->errorMsg = (string) $this->connection->error;

			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (ConnectionFailureException $e)
				{
					// If connect fails, ignore that exception and throw the normal exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}; Failed query: {sql}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg, 'sql' => $sql)
					);

					throw new ExecutionFailureException($sql, $this->errorMsg, $this->errorNum);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}

			// The server was not disconnected.
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}; Failed query: {sql}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg, 'sql' => $sql)
			);

			throw new ExecutionFailureException($sql, $this->errorMsg, $this->errorNum);
		}

		return $this->cursor;
	}
754816
private function doInsert(array $values) {
        $db       = $this->db();
        $mapping  = $this->dao()->getMapping();
        $table    = $mapping['table'];
        $idColumn = $mapping['identity']['column'];
        $id       = null;
        if  (isset($values[$idColumn])) $id = $values[$idColumn];
        else unset($values[$idColumn]);

        // translate column values
        foreach ($values as &$value) {
            $value = $db->escapeLiteral($value);
        }; unset($value);

        // create SQL statement
        $sql = 'insert into '.$table.' ('.join(', ', \array_keys($values)).')
                   values ('.join(', ', $values).')';

        // execute SQL statement
        if ($id) {
            $db->execute($sql);
        }
        else if ($db->supportsInsertReturn()) {
            $id = $db->query($sql.' returning '.$idColumn)->fetchInt();
        }
        else {
            $id = $db->execute($sql)->lastInsertId();
        }
        return $id;
    }
1091945
public static function ExecuteQuery ($query, array $conditions = [], array $values = [], array $options = []) {
		$options += $options + static::GetDefaultOptions();
		return DBI::ExecuteQuery($query, $conditions, $values, $options);
	}
715599
private function executeQueryIn(QueryBuilder $query, $field, array $values)
    {
        array_walk(
                $values,
                function(&$value, $key, $query) {
                    $value = $query->expr()->literal($value);
                },
                $query
        );

        return $query->where($query->expr()->in($field, $values))
                        ->execute()
                        ->fetchAll(\PDO::FETCH_COLUMN);
    }
510259
public function execute($params = null)
    {
        if (is_array($params)) {
            $hasZeroIndex = array_key_exists(0, $params);

            foreach ($params as $key => $val) {
                if ($hasZeroIndex && is_int($key)) {
                    $this->bindValue($key + 1, $val);
                } else {
                    $this->bindValue($key, $val);
                }
            }
        }

        if (! sasql_stmt_execute($this->stmt)) {
            throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt);
        }

        $this->result = sasql_stmt_result_metadata($this->stmt);

        return true;
    }
537515
function execQueryString($sql, $params = null)
    {
        if (!is_array($params) && !is_null($params)) {
            $params = array($params);
        }

        $stmt = $this->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }
319083
public function execute($sql = null, $parameters = array()) {
		if (empty($sql)) {
			return null;
		}
		$this->prepare($sql);
		$this->bind($parameters);
        Factory::log()->info(sprintf('MYSQLI: %s => %s', $sql,
            $this->getError()));
		return $this->result->execute();
	}
108693
public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
    {
        $id        = 0;
        $parameter = 0;
        $statement = $this->prepareStatement($query, $sql);
        $values    = $this->incrementBySequence($values, $sequence);
        $parameter = $this->bindValues($values, $statement, $parameter);
        $statement->bindParam($parameter, $id, PDO::PARAM_INT, 10);
        $statement->execute();

        return (int) $id;
    }
143252
function _query($sql,$inputarr=false)
	{
		$this->_errorMsg = false;
		if (is_array($inputarr)) {

			# bind input params with sp_executesql:
			# see http://www.quest-pipelines.com/newsletter-v3/0402_F.htm
			# works only with sql server 7 and newer
            $getIdentity = false;
            if (!is_array($sql) && preg_match('/^\\s*insert/i', $sql)) {
                $getIdentity = true;
                $sql .= (preg_match('/;\\s*$/i', $sql) ? ' ' : '; ') . $this->identitySQL;
            }
			if (!is_array($sql)) $sql = $this->Prepare($sql);
			$params = '';
			$decl = '';
			$i = 0;
			foreach($inputarr as $v) {
				if ($decl) {
					$decl .= ', ';
					$params .= ', ';
				}
				if (is_string($v)) {
					$len = strlen($v);
					if ($len == 0) $len = 1;

					if ($len > 4000 ) {
						// NVARCHAR is max 4000 chars. Let's use NTEXT
						$decl .= "@P$i NTEXT";
					} else {
						$decl .= "@P$i NVARCHAR($len)";
					}

					$params .= "@P$i=N". (strncmp($v,"'",1)==0? $v : $this->qstr($v));
				} else if (is_integer($v)) {
					$decl .= "@P$i INT";
					$params .= "@P$i=".$v;
				} else if (is_float($v)) {
					$decl .= "@P$i FLOAT";
					$params .= "@P$i=".$v;
				} else if (is_bool($v)) {
					$decl .= "@P$i INT"; # Used INT just in case BIT in not supported on the user's MSSQL version. It will cast appropriately.
					$params .= "@P$i=".(($v)?'1':'0'); # True == 1 in MSSQL BIT fields and acceptable for storing logical true in an int field
				} else {
					$decl .= "@P$i CHAR"; # Used char because a type is required even when the value is to be NULL.
					$params .= "@P$i=NULL";
					}
				$i += 1;
			}
			$decl = $this->qstr($decl);
			if ($this->debug) ADOConnection::outp("<font size=-1>sp_executesql N{$sql[1]},N$decl,$params</font>");
			$rez = mssql_query("sp_executesql N{$sql[1]},N$decl,$params", $this->_connectionID);
            if ($getIdentity) {
                $arr = @mssql_fetch_row($rez);
                $this->lastInsID = isset($arr[0]) ? $arr[0] : false;
                @mssql_data_seek($rez, 0);
            }

		} else if (is_array($sql)) {
			# PrepareSP()
			$rez = mssql_execute($sql[1]);
            $this->lastInsID = false;

		} else {
			$rez = mssql_query($sql,$this->_connectionID);
            $this->lastInsID = false;
		}
		return $rez;
	}