http://stackoverflow.com/questions/210564/getting-raw-sql-query-string-from-\PDO-prepared-statements
976336
public function debugQuery($sql, $params = array())
    {
        $keys = array();

        # build a regular expression for each parameter
        foreach ($params as $key => &$value)
        {
            if (is_string($key))
            {
                $keys[] = '/:' . $key . '/';
            }
            else
            {
                $keys[] = '/[?]/';
            }
            $value = '[#' . $value . '#]';
        }

        $query = preg_replace($keys, $params, $sql, 1, $count);

        return $query;
    }
645455
private function prepareStatement()
    {
        //Prepare statement
        $columns = "";
        $fields  = "";
        foreach ($this->fields as $key => $f) {
            if ($f == 'id') {
                continue;
            }
            if ($key == 1) {
                $columns .= "$f";
                $fields .= ":$f";
                continue;
            }

            $columns .= ", $f";
            $fields .= ", :$f";
        }

        $this->statement = $this->pdo->prepare(
            'INSERT INTO `' . $this->table . '` (' . $columns . ') VALUES (' . $fields . ')'
        );
    }
635443
function query($sql, $parms = array(), $alias = null)
    {
        $this->sql = $sql;
        $sth = $this->connect($alias)->prepare($sql);
        $sth->execute($parms);
        $this->rows = $sth->rowCount();
        $this->error[$sql] = $sth->errorInfo();

        if ($sth->columnCount() > 0) {
            return $this->result = $sth->fetchAll(PDO::FETCH_CLASS, __NAMESPACE__.'\Row', [$this->sql, $parms]);
        } else {
            $this->result = false;
            return $this->rows;
        }
    }
1209496
private function createQuery(): string
    {
        // 已经直接传递了SQL,Prepare与SQL相同
        $this->prepare = $this->sql;

        // 查找其中的表名
        $this->tables = $this->db->getNameFromQuery($this->sql);

        return $this->prepare;
    }
453936
public function getPrepopulateString()
    {
        $prepopulate_querystring = '';

        if (isset($_REQUEST['prepopulate']) && is_array($_REQUEST['prepopulate'])) {
            foreach ($_REQUEST['prepopulate'] as $field_id => $value) {
                // Properly decode and re-encode value for output
                $value = rawurlencode(rawurldecode($value));
                $prepopulate_querystring .= sprintf("prepopulate[%s]=%s&", $field_id, $value);
            }
            $prepopulate_querystring = trim($prepopulate_querystring, '&');
        }

        // This is to prevent the value being interpreted as an additional GET
        // parameter. eg. prepopulate[cat]=Minx&June, would come through as:
        // $_GET['cat'] = Minx
        // $_GET['June'] = ''
        $prepopulate_querystring = preg_replace("/&amp;$/", '', $prepopulate_querystring);

        return $prepopulate_querystring ? '?' . $prepopulate_querystring : null;
    }
161179
public function getQueryString()
    {
        $query = parent::getQueryString();
        if ($query) {
            $query .= '&';
        }

        if (!defined('REQUEST_TOKEN')) {
            throw new \RuntimeException('Request token not defined - can not append to query string.');
        }

        $query .= 'rt=' . REQUEST_TOKEN;

        return $query;
    }
569364
public function get_sql() : string {
		if ( empty( $this->columns_to_select ) ) {
			// this should be the default behavior
			$this->columns_to_select = [ '*' ];
		}

		$from = ' FROM ' . implode( ', ', $this->from ) . ' ';

		if ( ! empty( $this->joins ) ) {
			$from .= $this->joins;
		}

		$from  .= 'WHERE ' . $this->where_clause;
		$select = 'SELECT ' . implode( ', ', $this->columns_to_select ) . $from;

		if ( ! empty( $this->group_by ) ) {
			$select .= 'GROUP BY ' . implode( ', ', $this->group_by ) . ' ';
		}

		if ( $this->order_by !== '' ) {
			$select .= 'ORDER BY ' . $this->order_by . ' ';
		}

		$select .= 'LIMIT ' . $this->limit;

		if ( $this->offset !== '' ) {
			$select .= ' OFFSET ' . $this->offset;
		}

		return $select;
	}
57628
public function getStatement(string $query_string) : ResultSet
    {
        if (!$this->is_connected) {
            $this->connect();
        }
        $stmt = $this->dbconn->prepare($query_string);
        if (false === $stmt) {
            // The statement could not be prepared, return an appropriate exception
            throw new DatabaseQueryException('The query could not be prepared. | ' . $query_string . ' | ' . $this->dbconn->errorInfo()[2]);
        }
        return new ResultSetPDO($stmt);
    }
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;
	}
537212
public function getQueryString()
    {
        $qs = static::normalizeQueryString($this->getRequest()->server->get('QUERY_STRING'));

        return '' === $qs ? null : $qs;
    }
1361190
PreparedStatement getPreparedStatement(final SqlContext sqlContext) throws SQLException {
		Connection conn = null;
		if (sqlContext.getDbAlias() != null) {
			conn = getConnection(sqlContext.getDbAlias());
		} else {
			conn = getConnection();
		}

		if (conn == null) {
			throw new IllegalArgumentException(sqlContext.getDbAlias());
		}

		PreparedStatement stmt = null;
		switch (sqlContext.getSqlKind()) {
		case INSERT:
		case BULK_INSERT:
		case BATCH_INSERT:
			if (sqlContext.hasGeneratedKeyColumns()) {
				stmt = conn.prepareStatement(sqlContext.getExecutableSql(), sqlContext.getGeneratedKeyColumns());
			} else {
				stmt = conn.prepareStatement(sqlContext.getExecutableSql(), Statement.RETURN_GENERATED_KEYS);
			}
			break;
		case SELECT:
			stmt = conn.prepareStatement(sqlContext.getExecutableSql(),
					sqlContext.getResultSetType(),
					sqlContext.getResultSetConcurrency());
			break;
		default:
			stmt = conn.prepareStatement(sqlContext.getExecutableSql());
			break;
		}
		return sqlFilterManager.doPreparedStatement(sqlContext, stmt);
	}
467368
private function getPreparedSelect()
    {
        if (is_null($this->preparedSelect)) {
            $this->preparedSelect = $this->getServer()
                ->select()
                ->select($this->valueColumnName)
                ->from($this->tableName)
                ->where('AND')
                ->expr($this->keyColumnName, '=', ':id')
                ->begin('OR')
                ->expr($this->expireColumnName, '=', ':zero')
                ->expr($this->expireColumnName, '>', ':expire')
                ->end();
        }

        return $this->preparedSelect;
    }
569961
static public function show($raw_sql, $parameters)
    {
        $keys = array();
        $values = array();

        /*
         * Get longest keys first, sot the regex replacement doesn't
         * cut markers (ex : replace ":username" with "'joe'name"
         * if we have a param name :user )
         */
        $isNamedMarkers = false;
        if (count($parameters) && is_string(key($parameters))) {
            uksort($parameters, function($k1, $k2) {
                return strlen($k2) - strlen($k1);
            });
            $isNamedMarkers = true;
        }
        foreach ($parameters as $key => $value) {

            // check if named parameters (':param') or anonymous parameters ('?') are used
            if (is_string($key)) {
                $keys[] = '/:'.ltrim($key, ':').'/';
            } else {
                $keys[] = '/[?]/';
            }

            // bring parameter into human-readable format
            if (is_string($value)) {
                $values[] = "'" . addslashes($value) . "'";
            } elseif(is_int($value)) {
                $values[] = strval($value);
            } elseif (is_float($value)) {
                $values[] = strval($value);
            } elseif (is_array($value)) {
                $values[] = implode(',', $value);
            } elseif (is_null($value)) {
                $values[] = 'NULL';
            }
        }
        if ($isNamedMarkers) {
            return preg_replace($keys, $values, $raw_sql);
        } else {
            return preg_replace($keys, $values, $raw_sql, 1, $count);
        }
    }
355093
public function getSql()
    {
        $sqlTemplate = "SELECT %s FROM %s %s";
        $fieldsCompiled = implode(',', $this->getFields());
        return trim(sprintf(
            $sqlTemplate,
            $fieldsCompiled,
            $this->getTable(),
            $this->getWhereStatement()
        ));
    }
318384
protected function explain()
	{
		if ($this->query_sql === null) {
			$this->compile();
		}

		$sql = "\n    EXPLAIN\n" . $this->interpolateQuery($this->query_sql, $this->query_params);

		$explain = $this->pdo->query($sql);

		$data = $explain->fetchAll(\PDO::FETCH_ASSOC);
		$col_len = array();
		$t = "\n";

		// Calculate column widths
		foreach ($data as $row) {
			foreach ($row as $k => $v) {
				$col_len[$k] = isset($col_len[$k]) ? max($col_len[$k], strlen($v)) : strlen($v);
			}
		}
		foreach ($col_len as $k => $len) {
			$col_len[$k] = max($len, strlen($k));
		}

		// Horizontal Line
		foreach ($col_len as $k => $len) {
			$t .= '+'.str_repeat('-', $len + 2);
		}
		$t .= "+\n";

		// Table header
		foreach ($col_len as $k => $len) {
			$t .= sprintf('| %-'.$len.'s ', $k);
		}
		$t .= "+\n";

		// Horizontal Line
		foreach ($col_len as $k => $len) {
			$t .= '+'.str_repeat('-', $len + 2);
		}
		$t .= "+\n";

		// Table body
		foreach ($data as $row) {
			foreach ($row as $k => $v) {
				$t .= sprintf('| %-'.$col_len[$k].'s ', $v);
			}
			$t .= "|\n";
		}

		// Horizontal Line
		foreach ($col_len as $k => $len) {
			$t .= '+'.str_repeat('-', $len + 2);
		}
		$t .= "+\n";

		// Log the table
		if (function_exists('debug_msg')) {
			debug_msg('Explain last query:%s', $t);
		}

		// Make sure EXPLAIN query is destroyed.
		$this->uncompile();
	}
98763
public function getQuery()
    {
        $query = $this->database->getSelectQuery()->from($this->table);

        foreach ($this->join as $join) {
            if (!is_array($join[2])) {
                $join[2] = [$join[2]];
            }

            $where = array_shift($join[2]);
            if (!empty($join[2])) {
                foreach ($join[2] as $i => $value) {
                    $join[2][$i] = $this->database->bind($value);
                }

                $where = vsprintf($where, $join[2]);
            }

            $query->join($join[0], $join[1], $where, $join[3]);
        }

        foreach ($this->filter as $i => $filter) {
            //array('post_id=%s AND post_title IN %s', 123, array('asd'));
            $where = array_shift($filter);
            if (!empty($filter)) {
                foreach ($filter as $i => $value) {
                    $filter[$i] = $this->database->bind($value);
                }

                $where = vsprintf($where, $filter);
            }

            $query->where($where);
        }

        return $query;
    }
1093303
function _query($sql,$inputarr=false)
	{
		$rs = @ldap_search( $this->_connectionID, $this->database, $sql );
		$this->_errorMsg = ($rs) ? '' : 'Search error on '.$sql.': '.ldap_error($this->_connectionID);
		return $rs;
	}