Prepare a query. It returns a mysqli statement.
@param $query string
@return \mysqli_stmt returns the statement if correct otherwise null
@throws Exception
542844
public function prepare($query)
	{
		if (!$this->isOpen) { $this->throwError("It's not connected to the database",""); return null; }
		$this->lastParam=[];
		$this->lastQuery = $query;
		if ($this->readonly) {
			if (stripos($query, 'insert ') === 0 || stripos($query, 'update ') === 0 || stripos($query, 'delete ') === 0) {
				// we aren't checking SQL-DCL queries.
				$this->throwError("Database is in READ ONLY MODE","");
			}
		}
		if ($this->logLevel>=2) {
			$this->storeInfo($query);
		}

		try {
			$stmt = $this->conn1->prepare($query);
		} catch (Exception $ex) {
			$stmt=false;
			$this->throwError("Failed to prepare",$ex->getMessage(),json_encode($this->lastParam));
		}
		if ($stmt === false) {
			$this->throwError("Unable to prepare query",$this->lastQuery,json_encode($this->lastParam));
		}
		return $stmt;
	}
138216
function ExecuteQuery($query)
    {
        $this->lastQuery = $query;
        $result = mysqli_query($this->db, $query);
        $this->AssertSuccess();

        if ($result instanceof \mysqli_result)
            return new Reader($result);

        return null;
    }
24745
function executeQuery($query) {

        try {

            $table = FALSE;

            if (!is_null($query) && is_string($query)) {
                $connection = $this->getConnection();
                $resultQry = mysql_query($query, $connection);

                if ($resultQry) {

                    if (mysql_num_rows($resultQry) != 0) {

                        $rowTemplate = array();
                        $terminar = FALSE;
                        $cntCols = mysql_num_fields($resultQry);
                        $cnt = 0;

                        while (!$terminar) {

                            $nombreCampo = mysql_field_name($resultQry, $cnt);

                            if ($nombreCampo) {
                                $rowTemplate[$nombreCampo] = $nombreCampo;
                                $cnt = $cnt + 1;
                            }

                            $terminar = (( $cntCols - $cnt ) == 0);
                        }

                        $table = array();

                        while ($fila = mysql_fetch_assoc($resultQry)) {

                            $rowAux = $rowTemplate;

                            foreach ($rowAux as $k => $v) {
                                $rowAux[$k] = $fila[$k];
                            }

                            $table[] = $rowAux;
                        }

                        mysql_free_result($resultQry);
                    }

                    mysql_close($connection);
                } else {
                    throw new \Exception("SQL Error: " . mysql_error());
                }
            }

            return $table;
        } catch (\Exception $pEx) {
            throw new \Exception("Fallo al ejecutar la query: " . $query . "  " . $pEx->getMessage());
        }
    }
1109973
public function prepareQuery(Query $query)
    {
        $parameters = new Parameters($this->driver);

        if ($this->pdo === null)
            $this->connect();

        $sql = $this->driver->toSQL($parameters, $query);

        $statement = $this->prepare($sql);
        $parameters->bindParameters($statement);
        return $statement;
    }
1334384
public static function getRow($query)
    {
        $ret = null;

        $res = self::query($query);
        if ($res) {
            if ($row = self::connection()->sql_fetch_assoc($res)) {
                $ret = $row;
            }
            self::free($res);
        }

        return $ret;
    }
597523
protected function performQueryAnalysis($query)
    {
        $hints = [];
        if (preg_match('/^\\s*SELECT\\s*`?[a-zA-Z0-9]*`?\\.?\\*/i', $query)) {
            $hints[] = 'Use <code>SELECT *</code> only if you need all columns from table';
        }
        if (preg_match('/ORDER BY RAND()/i', $query)) {
            $hints[] = '<code>ORDER BY RAND()</code> is slow, try to avoid if you can.
				You can <a href="http://stackoverflow.com/questions/2663710/how-does-mysqls-order-by-rand-work" target="_blank">read this</a>
				or <a href="http://stackoverflow.com/questions/1244555/how-can-i-optimize-mysqls-order-by-rand-function" target="_blank">this</a>';
        }
        if (strpos($query, '!=') !== false) {
            $hints[] = 'The <code>!=</code> operator is not standard. Use the <code>&lt;&gt;</code> operator to test for inequality instead.';
        }
        if (stripos($query, 'WHERE') === false && preg_match('/^(SELECT) /i', $query)) {
            $hints[] = 'The <code>SELECT</code> statement has no <code>WHERE</code> clause and could examine many more rows than intended';
        }
        if (preg_match('/LIMIT\\s/i', $query) && stripos($query, 'ORDER BY') === false) {
            $hints[] = '<code>LIMIT</code> without <code>ORDER BY</code> causes non-deterministic results, depending on the query execution plan';
        }
        if (preg_match('/LIKE\\s[\'"](%.*?)[\'"]/i', $query, $matches)) {
            $hints[] = 	'An argument has a leading wildcard character: <code>' . $matches[1]. '</code>.
								The predicate with this argument is not sargable and cannot use an index if one exists.';
        }
        return $hints;
    }
138225
public function statement( $query, $params = array() )
	{
		// we alway prepare the query even if we dont have parameters
		$sth = $this->driver()->connection()->prepare( $query );
		
		// because we set pdo the throw exception on db errors
		// we catch them here to throw our own exception.
		try 
		{
			$sth->execute( $params );
		}
		catch ( \PDOException $e ) 
		{
			throw new Exception( "DB\\Handler - PDOException: {$e->getMessage()} \n Query: {$query}" );
		}
		
		// In development we alway log the query into an array.
		if ( \ClanCats::in_development() ) 
		{	
			$keys = array();
			
			foreach ( $params as $key => $value ) 
			{
				if ( is_string( $key ) ) 
				{
					$keys[] = '/:'.$key.'/';
				} else {
					$keys[] = '/[?]/';
				}
			}
			
			static::$_query_log[] = preg_replace( $keys, $params, $query, 1 );
		}
		
		return $sth;
	}
697433
public function execute($query)
    {
        $this->_queries[] = $query;

        $sql = is_string($query) ? $query : $query->getString();

        $resultSQL = $this->getAdapter()->execute($sql);
        $result = new Result($resultSQL, $this->getAdapter());
        $result->setQuery($query);

        return $result;
    }
1352699
public function query($database, $query, $parameters = [])
    {
        $driver = $this->getDriver();

        if (!$driver instanceof QueryDriverInterface) {
            throw new Exception('The currently configured driver does not support query operations');
        }

        if ($database) {
            $parameters['db'] = $database;
        }

        $parameters = [
            'url' => 'query?' . http_build_query(array_merge(['q' => $query], $parameters)),
            'database' => $database,
            'method' => 'get'
        ];

        // add authentication to the driver if needed
        if (!empty($this->username) && !empty($this->password)) {
            $parameters += ['auth' => [$this->username, $this->password]];
        }

        $driver->setParameters($parameters);

        try {
            // store the last query sent
            static::$lastQuery = $query;

            // perform the query and return the resultset
            return $driver->query();

        } catch (\Exception $e) {
            throw new Exception('Query has failed', $e->getCode(), $e);
        }
    }
108590
private function executeQuery($query, $data = null) {
        $stmt = $this->conn->prepare($query);
        $stmt->execute($data);
        
        return $stmt;
    }
381487
protected function executeQuery($query)
    {
        $query   = null !== $this->getLocale() ? sprintf('%s&language=%s', $query, $this->getLocale()) : $query;
        $content = $this->getAdapter()->get($query)->getBody();

        if (!$data = json_decode($content, true)) {
            throw new NoResult(sprintf('Could not execute query: %s', $query));
        }

        if (!isset($data['Response']) && 'InvalidCredentials' === $data['subtype']) {
            throw new InvalidCredentials(sprintf('Invalid credentials: %s', $data['details']));
        } elseif (!isset($data['Response'])) {
            throw new NoResult(
                sprintf('Error type `%s` returned from api `%s`', $data['subtype'], $data['Details'])
            );
        }

        if (empty($data['Response']['View'])) {
            throw new NoResult(sprintf('Could not find results for given query: %s', $query));
        }

        $locations = $data['Response']['View'][0]['Result'];

        $results = array();
        foreach ($locations as $location) {
            $location       = $location['Location'];
            $coordinates    = isset($location['NavigationPosition'][0]) ? $location['NavigationPosition'][0] : $location['DisplayPosition'];
            $bounds         = $location['MapView'];
            $address        = $location['Address'];
            $additionalData = $location['Address']['AdditionalData'];

            $results[] = array_merge($this->getDefaults(), array(
                'latitude'     => $coordinates['Latitude']  ?: null,
                'longitude'    => $coordinates['Longitude'] ?: null,
                'bounds'       => array(
                    'south' => $bounds['BottomRight']['Latitude']  ?: null,
                    'west'  => $bounds['TopLeft']['Longitude']     ?: null,
                    'north' => $bounds['TopLeft']['Latitude']      ?: null,
                    'east'  => $bounds['BottomRight']['Longitude'] ?: null,
                ),
                'streetNumber' => isset($address['HouseNumber']) ? $address['HouseNumber'] : null,
                'streetName'   => isset($address['Street'])      ? $address['Street']      : null,
                'city'         => isset($address['City'])        ? $address['City']        : null,
                'cityDistrict' => isset($address['District'])    ? $address['District']    : null,
                'zipcode'      => isset($address['PostalCode'])  ? $address['PostalCode']  : null,
                'county'       => isset($address['County'])      ? $address['County']      : null,
                'regionCode'   => isset($address['State'])       ? $address['State']       : null,
                'countryCode'  => isset($address['Country'])     ? $address['Country']     : null,
                'region'       => $this->findByKey('StateName', $additionalData),
                'country'      => $this->findByKey('CountryName', $additionalData),
                'countyCode'   => null,
            ));
        }

        return $results;
    }
508113
protected function prepareQuery($query)
    {
        $query = $query->with($this->withs);

        if ($this->withCounts) {
            $query = $query->withCount($this->withCounts);
        }

        if ($this->orderBy) {
            $query = $query->orderBy($this->orderBy, $this->orderByDirection);
        }

        if ( ! empty($this->has)) {
            foreach ($this->has as $has) {
                $query = $query->has($has['relation'], $has['operator'], $has['value']);
            }
        }

        if ( ! empty($this->whereHas)) {
            foreach ($this->whereHas as $has) {
                $query = $query->whereHas($has[0], isset($has[1]) ? $has[1] : null);
            }
        }

        return $query;
    }
877423
public function query($query)
    {

        if (empty($query) || !$this->db) {
            return false;
        }


        // if the resource type is not a mysql link it should try to reconnect
        if (!$this->db->isConnected()) {
            $this->db->ping();
        }

        // the last sql query
        $this->lastSql = (string)$query;


        // if the master is down a select may query the slave but it should not
        // insert anything
        if ($this->slaveConnection === $this->db && stripos(trim($query), 'SELECT') !== 0) {
            throw new DatabaseException(__METHOD__ . ' no Select on slave, abort !!', self::ERR_CONN, self::SEVERITY_LOG, __FILE__, __LINE__);
        }

        // tries execute the query and fetches the result
        $res             = $this->db->getDbAdapter()->query($query);


        try {
            // in cases of errors
            if (!$res) {
                $this->error   = $this->db->getDbAdapter()->getErrorInfo();
                $this->errorno = $this->db->getDbAdapter()->getErrorCode();
                throw new DatabaseException(__METHOD__ . "\nsql: $this->lastSql\nsql_error:$this->error\nsql_errorno:$this->errorno", self::ERR_EXEC, self::SEVERITY_LOG, __FILE__, __LINE__);
            } else {
                $this->insert_id = $this->db->getDbAdapter()->getLastInsertId();
            }
        } catch (DatabaseException $e) {
            if (Config::get('use_exception') !== true) {
                return false;
            }
            throw $e;
        }

        // reset old errors
        $this->error         = '';
        $this->errorno       = 0;
        if ($res && $res instanceof \PDOStatement){
            $this->affected_rows = $this->db->getDbAdapter()->getAffectedRows($res);
        }

        return $res;
    }
694091
protected function exec($query)
    {
        try {
            Connect::getConn()->exec($query);
        } catch (Exception $e) {
            static::$response["status"] = "error";
            static::$response["response"] = $e->getMessage();
            static::$response["code"] = $e->getCode();

            return static::terminate(static::$response);
        }
        return null;
    }
867364
public function prepare($query, $args = null) {

		if(strlen($query) === 0) return;

		if(!is_array($args)) {
			$args = func_get_args();
			array_shift($args);
		}


		$query = str_replace(array("'?'", '"?"'), '?', $query);
		$query = preg_replace('/\?/', '%s', $query);
		$args = array_map(array($this, 'escape'), $args);

		return @vsprintf($query, $args);

	}
597897
public function getQuery(): Query
    {
        if (count($this->what) == 0) {
            throw new Exception('Can not build UPDATE query, SET is not defined');
        }

        if ($this->table === null) {
            throw new Exception('Can not build UPDATE query when table name is not set');
        }

        $sql = "UPDATE {$this->table}\nSET\n";

        foreach ($this->what as $field => $value) {
            $sql .= "\t{$field} = ";
            if ($value instanceof Expr) {
                $sql .= "{$value},\n";
            } else {
                //$key = $this->bind($field, $value);
	            $key = $this->getBindings()->makeAndSet($field, $value);
                $sql .= ":{$key},\n";
            }
        }

        $sql = substr($sql, 0, -2);

        if ($this->hasWhere()) {
            $sql .= "\nWHERE{$this->getWhereSql()}";
        }

        if (count($this->orderBy) > 0) {
            $sql .= "\nORDER BY";
            foreach ($this->orderBy as $r) {
                $sql .= "\n\t{$r['field']} {$r['direction']},";
            }
            $sql = substr($sql, 0, -1);
        }

        return new Query($sql, $this->getBindings(), $this->getAdapterConnection());
    }
269015
public function setQuery(string $query, ?PDO $db = null)
    {
        if ($db == null) {
            $db = MDbConnection::getDbConnection();
        }

        if ($db instanceof \PDO) {
            $this->query = new MPDOQuery($query, $db);
        } else {
            throw new \Exception("Database connection not supported.");
        }

        $this->query->exec();
    }