Common DB query
@param string $q
@param bool $return_inserted_id

@return PDOStatement | int
499251
public function sql_query($q, $return_inserted_id = false)
    {
        if (!$this->pdo_db) {
            $this->connect();
        }

        $q = trim($q);

        // Set query start time if debug is enabled or if we analyze queries
        if (Settings::get('debug_panel') || Settings::get('analyze_db_queries')) {
            $ts = microtime(true);
        }

        /** @var PDOStatement $pdo_query */
        $pdo_query = $this->pdo_db->query($q);

        if (!$pdo_query) {
            $err = $this->pdo_db->errorInfo()[2];

            trigger_error($err . '<br><br>Query:<br><br>' . $q);
        }

        if (isset($ts)) {
            // Start time exists - so we save query to analyze
            $tt = microtime(true) - $ts;

            if (Settings::get('debug_panel')) {
                Stats::addQuery([
                    'query' => $q,
                    'backtrace' => debug_backtrace(),
                    'time' => $tt
                ]);
            }

            if (Settings::get('analyze_db_queries')) {
                QueryAnalyzer::getInstance()
                    ->addQuery($q, $tt);
            }
        }

        return $return_inserted_id ? $this->pdo_db->lastInsertId() : $pdo_query;
    }
878118
function getQueryStatement(PDO $conn = null) {
		if (0 === count($this->conds)) {
			return null;
		}

		$stmnt = new QueryStatement($conn);

		$is_first = true;
		$is_second = false;
		foreach ($this->conds as &$cond) {
			$cond_stmnt = null;

			// avoid call_user_func_array for better stack traces
			switch (count($cond[1])) {
				case 1:
					$cond_stmnt = self::processCondition($cond[1][0]);
					break;
				case 2:
					$cond_stmnt = self::processCondition($cond[1][0], $cond[1][1]);
					break;
				case 3:
					$cond_stmnt = self::processCondition($cond[1][0], $cond[1][1], $cond[1][2]);
					break;
				case 4:
					$cond_stmnt = self::processCondition($cond[1][0], $cond[1][1], $cond[1][2], $cond[1][3]);
					break;
			}

			if (null === $cond_stmnt) {
				continue;
			}

			if ($is_first) {
				$sep = '';
				$is_first = false;
				$is_second = true;
			} else {
				$sep = (($is_second && 'OR' === $this->conds[0][0]) ? 'OR' : $cond[0]) . ' ';
				$is_second = false;
			}

			$stmnt->string .= "\n\t$sep" . $cond_stmnt->string;
			$stmnt->addParams($cond_stmnt->params);
			$stmnt->addIdentifiers($cond_stmnt->identifiers);
		}
		return $stmnt;
	}
1011768
static function addPhrase( $phrase, $returnCount )
    {
        $db = eZDB::instance();
        $db->begin();
        $db->lock( "ezsearch_search_phrase" );

        $trans = eZCharTransform::instance();
        $phrase = $trans->transformByGroup( trim( $phrase ), 'search' );

        // 250 is the numbers of characters accepted by the DB table, so shorten to fit
        if ( strlen( $phrase ) > 250 )
        {
            $phrase = substr( $phrase , 0 , 247 ) . "...";
        }
        $phrase = $db->escapeString( $phrase );

        // find or store the phrase
        $phraseRes = $db->arrayQuery( "SELECT id FROM ezsearch_search_phrase WHERE phrase='$phrase'" );

        if ( count( $phraseRes ) == 1 )
        {
            $phraseID = $phraseRes[0]['id'];
            $db->query( "UPDATE ezsearch_search_phrase
                         SET    phrase_count = phrase_count + 1,
                                result_count = result_count + $returnCount
                         WHERE  id = $phraseID" );
        }
        else
        {
            $db->query( "INSERT INTO
                              ezsearch_search_phrase ( phrase, phrase_count, result_count )
                         VALUES ( '$phrase', 1, $returnCount )" );
        }
        $db->unlock();
        $db->commit();
    }
1332527
public static function post(
        $attributes,
        $return = \Phramework\Database\Operations\Create::RETURN_ID
    ) {
        return \Phramework\Database\Operations\Create::create(
            $attributes,
            static::getTable(),
            static::getSchema(),
            $return
        );
    }
1299288
public function insertRecord($entity, $returnEntity = true, $doFlush = true)
    {
        $this->manager->persist($entity);

        if ($doFlush) {
            $this->manager->flush($entity);
        }

        // Fire ModelEvent
        $this->dispatchModelEvent(ModelEvent::MODEL_EVENT_INSERT, $entity);

        if ($returnEntity) {
            return $this->find($entity->getId());
        }
        return null;
    }
1374089
public function query(QueryInterface $query, $return = false)
    {
        DebuggerUtility::var_dump(
            $this->queryParser->parseQuery($query),
            null,
            8,
            false,
            true,
            $return
        );
    }
687783
public function insert()
    {
        if (is_null($this->sth)) {
            throw new QueryFailedException();
        }

        return ($this->dbh->lastInsertId() > 0) ? $this->dbh->lastInsertId() : false;
    }
220627
function _query($sql,$inputarr=false)
	{
		$rez = $this->_connectionID->query($sql);
		if ($rez === false) {
			$this->_errorNo = $this->_connectionID->lastErrorCode();
		}
		// If no data was returned, we don't need to create a real recordset
		elseif ($rez->numColumns() == 0) {
			$rez->finalize();
			$rez = true;
		}

		return $rez;
	}
1346757
public function getQuery()
    {
        $multiValList = [];
        foreach ($this->setVal as $val) {
            $multiValList[] = '('.implode(', ', $val).')';
        }
        
        return 'INSERT INTO '
            . $this->table . ' ('.implode(', ', $this->setKey)
            . ') VALUES ' . implode(", \n", $multiValList).';';
    }
564068
public function query($q = null)
    {
        return User::where(function ($query) use ($q) {
            $query->where('email', 'like', "%{$q}")
                ->orWhere('name', 'like', "%{$q}");
        })->orderBy('email')->paginate();
    }
58820
public static function ExecuteEach()
	{
		$arguments = func_get_args();
		$executeQueryBuilders = is_array($arguments[0])? $arguments[0] : $arguments;

		$db = self::connect();
		$db->beginTransaction();
		
		try
		{
			$results = null;

			foreach($executeQueryBuilders as $executeQueryBuilder)
			{				
				$executeQuery = $executeQueryBuilder($results);
				$query = $db->prepare($executeQuery["statement"]);
			
				foreach($executeQuery["parameters"] as $key => $parameter)
				{
					if(!isset($parameter["type"]))
						$parameter["type"] = PDO::PARAM_STR;
						
					$query->bindParam($key,$parameter["value"],$parameter["type"]);
				}
					
				$query->execute();
				$rowsAffected = $query->rowCount();
				$lastID = $db->lastInsertId();

				$results = (object) array(
					DatabaseReturn::RowsAffected => $rowsAffected,
					DatabaseReturn::LastInsertID => $lastID
				);
			}
		}
		catch (PDOException $e)
		{
			$db->rollBack();
			$exception = "Sorry, there was a problem with query execution. ({$e->getMessage()})";
		}

		if($exception) throw new \Exception($exception);
		
		$db->commit();
		return $results;
	}
1031771
protected function _query()
    {
        if ($this->_q)
            return $this->_q;

        $db = $this->gateway;
        if ($this->persist) {
            $db = $db->withOptions([
                'typeMap' => $this->typeMap,
            ]);
        }

        $this->_q = $db->selectCollection($this->collection_name);
        return $this->_q;
    }
8118
public function query($sql)
    {
        if (true == Config::get('sql_log')) {
            wlog('SQL-Log', $sql);
        }

        $_key = strtolower(substr($sql, 0, 6));
        if ($_key == 'select') {
            $qt = 'query';
        } else {
            $qt = 'exec';
        }

        if (true == ($rs = $this->db->$qt($sql))) {
            $GLOBALS['__$DB_QUERY_COUNT']++;
            return $rs;
        } else {
            \show_error('DB_ERROR: ' . $this->db->lastErrorMsg() . "\nRAW_SQL: " . $sql);
        }
        //return false;
    }
412489
function _query($sql,$inputarr=false)
	{
	global $ADODB_COUNTRECS;

		if ($ADODB_COUNTRECS == false && ADODB_PHPVER >= 0x4300)
			return sybase_unbuffered_query($sql,$this->_connectionID);
		else
			return sybase_query($sql,$this->_connectionID);
	}
771823
public function query($q, $params = array()){
		try{
			if(!empty($this->pdo)){
				$this->st = $this->pdo->prepare($q);
				if(!empty($params)){
					$keys = array_keys($params);
					$qmark = false;//qmark = question mark
					if(is_int($keys[0])){//mode '?'
						$qmark = true;
					}

					foreach($params as $p => $val){
						if($qmark){
							//$p is a numeric - 0, 1, 2, ...
							$p += 1;//bindValue starts to 1
						}
						if(is_array($val) && count($val) == 2){//if called with PDO::PARAM_STR or PDO::PARAM_INT, PDO::PARAM_BOOL
							$this->st->bindValue($p, $val[0], $val[1]);
						}
						else{
							if(! is_bool($val)) { //fix fatal error with some php versions
								$this->st->bindValue($p, $val);
							}
							else {
								$this->st->bindValue($p, $val, PDO::PARAM_INT);//cast
							}
						}
					}
				}

				$this->st->execute();
				return $this->st;
			}
			else{
				throw new DBException('PDO attribute is undefined');
			}
		}
		catch(\Exception $e){
			throw new DBException($e->getMessage(), $e->getCode());
		}
	}
393521
protected function insert() {
		$conn = static::getConnection();
		$pk = static::getPrimaryKey();

		$fields = array();
		$values = array();
		$placeholders = array();
		foreach (static::$_columns as $column_name => &$type) {
			$value = $this->$column_name;
			if ($value === null && !$this->isColumnModified($column_name))
				continue;
			$fields[] = $conn->quoteIdentifier($column_name, true);
			$values[] = $value;
			$placeholders[] = '?';
		}

		$quoted_table = $conn->quoteIdentifier(static::getTableName(), true);
		$query_s = 'INSERT INTO ' . $quoted_table . ' (' . implode(', ', $fields) . ')';

		if ($pk && $this->isAutoIncrement() && $conn instanceof DBMSSQL) {
			$query_s .= " OUTPUT inserted.$pk";
		}

		$query_s .= ' VALUES (' . implode(', ', $placeholders) . ') ';

		if ($pk && $this->isAutoIncrement() && $conn instanceof DBPostgres) {
			$query_s .= ' RETURNING ' . $conn->quoteIdentifier($pk, true);
		}

		$statement = new QueryStatement($conn);
		$statement->setString($query_s);
		$statement->setParams($values);

		$result = $statement->bindAndExecute();
		$count = $result->rowCount();

		if ($pk && $this->isAutoIncrement()) {
			$id = null;
			if (($conn instanceof DBPostgres) || ($conn instanceof DBMSSQL)) {
				$id = $result->fetchColumn(0);
			} elseif ($conn->isGetIdAfterInsert()) {
				$id = $conn->lastInsertId();
				if (empty($id) && $conn instanceof DBRedshift) {
					$id = $conn->query('SELECT MAX(' . $conn->quoteIdentifier($pk) . ") FROM $quoted_table")->fetchColumn();
				}
			}
			if (null !== $id) {
				$this->{"set$pk"}($id);
			}
		}

		$this->resetModified();
		$this->setNew(false);

		$this->insertIntoPool($this);

		return $count;
	}
520184
public function query($q, $cb = null)
    {
        if ($this->finished) {
            throw new ConnectionFinished;
        }
        return $this->command(Pool::COM_QUERY, $q, $cb);
    }