Returns prepared PDO statement
For internal usage only, regarding its public visibility

@throws \RuntimeException If bindings contain nested arrays
@return \PDOStatement
355347
public function getStmt()
    {
        // Make sure there are no nested arrays
        if (ArrayUtils::hasAtLeastOneArrayValue($this->bindings)) {
            throw new RuntimeException('PDO bindings can not contain nested arrays');
        }

        // Build target query before bindings are cleared purely for logging purpose
        $log = str_replace(array_keys($this->bindings), array_values($this->bindings), $this->queryBuilder->getQueryString());

        // Execute it
        $stmt = $this->pdo->prepare($this->queryBuilder->getQueryString());
        $stmt->execute($this->bindings);

        // Log target query
        $this->queryLogger->add($log);

        // Clear the buffer
        $this->clear();

        return $stmt;
    }
1037536
public function update(array $data): \PDOStatement
    {
        /**
         * @var $response \PDOStatement
         */
        $queryObject = $this->getQuery('update', $data);

        $this->connection->setLastQuery($queryObject);

        $this->fireEvents(EventHandler::EVENT_BEFORE_UPDATE, $queryObject);

        [$response, $executionTime] = $this->statement($queryObject->getSql(), $queryObject->getBindings());

        $this->fireEvents(EventHandler::EVENT_AFTER_UPDATE, $queryObject, [
            'execution_time' => $executionTime,
        ]);

        return $response;
    }
1041831
private function getPdoStatement($statement)
    {
        try {
            if (false === $sth = $this->pdo->prepare($statement)) {
                throw new \Exception(sprintf('Can not prepare this pdo statement: "%s"', $statement));
            }
        } catch (\Exception $e) {
            throw $e;
        }

        return $sth;
    }
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 . ')'
        );
    }
1042855
public static function getConection() : \PDO
    {
        if (self::$instance === null) {
            $con = self::findData();
            self::$instance = new \PDO("mysql:host=".$con['HOST'].";dbname=".$con['DBNAME'], $con['USER'], $con['PASS']);
            self::$instance->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
                
        }
        return self::$instance;
    }
776067
public function execute()
    {
        $statement = $this->getPdoStatement();
        $result = $statement->execute($this->bindings);
        if (!$result) {
            $errorInfo = $statement->errorInfo();
            throw new RuntimeException(
                $errorInfo[1],
                $errorInfo[2]
            );
        }
        return $statement;
    }
1071192
protected function bindParameters(\PDOStatement $statement, array $parameters, $prefix = '')
    {
        foreach ($parameters as $key => $value) {
            // In case of multiple rows are given for insert statement
            if (is_array($value)) {
                $statement = $this->bindParameters($statement, $value, $prefix . $key);
            } else {
                switch (true) {
                    case is_int($value):
                        $type = \PDO::PARAM_INT;
                        break;
                    case is_bool($value):
                        $type = \PDO::PARAM_BOOL;
                        break;
                    case $value === null:
                        $type = \PDO::PARAM_NULL;
                        break;
                    case $value instanceof \DateTimeInterface:
                        $type  = \PDO::PARAM_STR;
                        $value = $value->format('Y-m-d H:i:s.u');
                        break;
                    default:
                        $type = \PDO::PARAM_STR;
                }

                $statement->bindValue($prefix . $key, $value, $type);
            }
        }

        return $statement;
    }
1118041
public function get_statement( $db ) {
		$statement = $db->prepare( $this->get_sql() );
		foreach ( $this->values_to_bind as $name => $value ) {
			if ( false === $value['data_type'] ) {
				$statement->bindValue( $name, $value['value'] );
			} else {
				$statement->bindValue( $name, $value['value'], $value['data_type'] );
			}
		}
		return $statement;
	}
1105630
protected function db()
    {
        if (!isset($this->database)) {
            throw new RuntimeException(sprintf(
                'Database Connection is not defined for "%s"',
                get_class($this)
            ));
        }

        return $this->database;
    }
57320
public function bind(PDOStatement $pdo_statement, array $data = [])
    {
        foreach ($data as $key => $value) {
            if (is_null($value) || strtolower($value) === 'null') {
                $pdo_statement->bindValue(
                    ':' . $key,
                    $value,
                    PDO::PARAM_NULL
                );
                
                unset($data[$key]);
            }
        }

        foreach ($data as $key => $value) {
            $param = PDO::PARAM_INT;

            if (preg_match('/[a-z0-9A-Z_-]+|éàèëïùöôîüµ$£!?\.\+,;:/', $value) && !is_numeric($value)) {
                /**
                 * SECURITY OF DATA
                 * - Injection SQL
                 * - XSS
                 */
                $param = PDO::PARAM_STR;
            } else {
                /**
                 * We force the value in whole or in reel.
                 */
                if (is_int($value)) {
                    $value = (int) $value;
                } elseif (is_float($value)) {
                    $value = (float) $value;
                } else {
                    $value = (double) $value;
                }
            }

            if (is_string($key)) {
                $pdo_statement->bindValue(':' . $key, $value, $param);
            } else {
                $pdo_statement->bindValue($key + 1, $value, $param);
            }
        }

        return $pdo_statement;
    }
931568
public function execute()
	{
		$this->connect();

		if (!is_object($this->connection))
		{
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg)
			);
			throw new \RuntimeException($this->errorMsg, $this->errorNum);
		}

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

		if ($this->limit > 0 || $this->offset > 0)
		{
			// @TODO
			$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
		}

		// 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 \PDOStatement)
		{
			// Bind the variables:
			if ($this->sql instanceof PreparableInterface)
			{
				$bounded =& $this->sql->getBounded();

				foreach ($bounded as $key => $obj)
				{
					$this->prepared->bindParam($key, $obj->value, $obj->dataType, $obj->length, $obj->driverOptions);
				}
			}

			$this->executed = $this->prepared->execute();
		}

		// If an error occurred handle it.
		if (!$this->executed)
		{
			// Get the error number and message before we execute any more queries.
			$errorNum = (int) $this->connection->errorCode();
			$errorMsg = (string) 'SQL: ' . implode(", ", $this->connection->errorInfo());

			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (\RuntimeException $e)
				// If connect fails, ignore that exception and throw the normal exception.
				{
					// Get the error number and message.
					$this->errorNum = (int) $this->connection->errorCode();
					$this->errorMsg = (string) 'SQL: ' . implode(", ", $this->connection->errorInfo());

					// Throw the normal query exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg)
					);
					throw new \RuntimeException($this->errorMsg, $this->errorNum);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}
			else
			// The server was not disconnected.
			{
				// Get the error number and message from before we tried to reconnect.
				$this->errorNum = $errorNum;
				$this->errorMsg = $errorMsg;

				// Throw the normal query exception.
				$this->log(
					Log\LogLevel::ERROR,
					'Database query failed (error #{code}): {message}',
					array('code' => $this->errorNum, 'message' => $this->errorMsg)
				);
				throw new \RuntimeException($this->errorMsg, $this->errorNum);
			}
		}

		return $this->prepared;
	}
620611
public function render()
    {
        /** @var Grid $grid */
        $grid = $this->root;
        $this->isTotalsCalculationFinished = true;
        $tr = $grid->getRecordView();
        // set total_row as current grid row
        $lastRow = $grid->getCurrentRow();
        $grid->setCurrentRow($this->totalData);

        // modify columns, prepare it for rendering totals row
        $valueCalculators = [];
        $valueFormatters = [];
        foreach ($grid->getColumns() as $column) {
            $valueCalculators[$column->getId()] = $column->getValueCalculator();
            $valueFormatters[$column->getId()] = $prevFormatter = $column->getValueFormatter();
            $column->setValueCalculator(null);
            $column->setValueFormatter(function ($value) use ($prevFormatter, $column) {
                $operation = $this->getOperation($column->getId());
                if ($prevFormatter && !($operation === static::OPERATION_IGNORE || $operation instanceof Closure)) {
                    $value = call_user_func($prevFormatter, $value);
                }
                // Add value prefix if specified for operation
                if ($value !== null && is_string($operation) && array_key_exists($operation, $this->valuePrefixes)) {
                    $value = $this->valuePrefixes[$operation] . '&nbsp;' . $value;
                }
                return $value;
            });
        }

        $output = $tr->render();

        // restore column value calculators & formatters
        foreach ($grid->getColumns() as $column) {
            $column->setValueCalculator($valueCalculators[$column->getId()]);
            $column->setValueFormatter($valueFormatters[$column->getId()]);
        }
        // restore last data row
        $grid->setCurrentRow($lastRow);
        return $output;
    }
592946
private function pdoPrepare($sql)
    {
        try {
            $pdoStatement = $this->getPdo()->prepare($sql);
        } catch (\PDOException $e) {
            throw new \RuntimeException("Failed to prepare SQL query: {$sql} << {$e->getMessage()}", 0, $e);
        }

        return $pdoStatement;
    }
1082652
private function binding(\PDOStatement $sql, array $bindings = []): \PDOStatement
    {
        foreach ($bindings as $binding=>$value) {
            if (!is_array($value)) {
                $sql->bindValue($binding, $value);
            } else {
                switch(strtolower($value[1])) {
                    case 'date':
                        $sql->bindValue($binding, $this->time($value[0], 'Y-m-d'), \PDO::PARAM_STR);
                        break;
                    case 'time':
                        $sql->bindValue($binding, $this->time($value[0], 'Y-m-d H:i:s.u'), \PDO::PARAM_STR);
                        break;
                    case 'bool':
                    case 'boolean':
                        $sql->bindValue($binding, boolval($value[0]), \PDO::PARAM_BOOL);
                        break;
                    case 'null':
                        $sql->bindValue($binding, NULL, \PDO::PARAM_NULL);
                        break;
                    case 'int':
                    case 'integer':
                    case 'number':
                    case 'limit':
                    case 'offset':
                        $sql->bindValue($binding, intval($value[0]), \PDO::PARAM_INT);
                        break;
                    case 'str':
                    case 'string':
                    case 'text':
                    case 'float':
                    case 'varchar':
                    case 'varchar2':
                        $sql->bindValue($binding, strval($value[0]), \PDO::PARAM_STR);
                        break;
                    case 'lob':
                    case 'large':
                    case 'object':
                    case 'blob':
                        $sql->bindParam($binding, $value[0], \PDO::PARAM_LOB, strlen($value[0]));
                        break;
                    case 'like':
                        $sql->bindValue($binding, '%'.$value[0].'%', \PDO::PARAM_STR);
                        break;
                    default:
                        if (is_int($value[1])) {
                            $sql->bindValue($binding, $value[0], $value[1]);
                        } else {
                            $sql->bindValue($binding, strval($value[0]), \PDO::PARAM_STR);
                        }
                }
            }
        }
        return $sql;
    }
1166493
public function buildCountStatement()
	{
		if( !$this->keys )
			throw new RuntimeException( 'No Columns defined.' );
		if( !$this->tables )
			throw new RuntimeException( 'No Tables defined.' );

		$tables		= array();
		$tables		= "\nFROM\n\t".implode( ",\n\t", $this->tables );
		$conditions	= "";
		$groupings	= "";
		$havings	= "";
		if( $this->conditions )
			$conditions	= "\nWHERE\n\t".implode( " AND\n\t", $this->conditions );
		if( $this->groupings )
			$groupings	= "\nGROUP BY\n\t".implode( ",\n\t", $this->groupings );
		if( $this->havings )
			$havings	= "\nHAVING\n\t".implode( ",\n\t", $this->havings );
		$column	= preg_replace( '/(.+)( AS .+)/i', '\\1', $this->keys[0] );
		$statement = "SELECT COUNT(".$column.") as rowcount".$tables.$conditions.$groupings.$havings;
		return $statement;
	}
332161
function bindAndExecute() {
		$conn = $this->connection;

		if ($conn === null) {
			throw new RuntimeException('bindAndExecute cannot be called on a QueryStatement without a connection.');
		}
		if ($conn instanceof DBMSSQL && $conn->getDriver() === 'dblib' && function_exists('mb_detect_encoding')) {
			return $conn->query($this->__toString());
		}
		if ($conn instanceof DBSQLite) {
			return $conn->query($this->__toString());
		}

		$string = self::embedIdentifiers($this->getString(), array_values($this->identifiers), $conn);

		$result = $conn->prepare($string);
		foreach ($this->getParams() as $key => $value) {
			$pdo_type = PDO::PARAM_STR;
			if (is_int($value)) {
				$pdo_type = PDO::PARAM_INT;
			} elseif (is_null($value)) {
				$pdo_type = PDO::PARAM_NULL;
			} elseif (is_bool($value)) {
				$value = $value ? 1 : 0;
				$pdo_type = PDO::PARAM_INT;
			}
			$result->bindValue($key + 1, $value, $pdo_type);
		}
		$result->execute();
		return $result;
	}
1021811
protected function provideStatement(): \PDOStatement
    {
        $sqlStatement = $this->buildStatement();
        $bindingValues = $this->statementBuilder->getBindingValues();
        return $this->prepareStatement($sqlStatement, $bindingValues);
    }