TODO: For the love of god, rewrite this to use PDO prepared statements
422837
public function processInsert(DatabaseLayer\Insert $thing)
    {
        // SELECTORS
        if (count($thing->getTables()) > 1) {
            throw new Exception("Active Record Cannot insert into more than one table at a time!");
        }
        $tables = $thing->getTables();
        $table = end($tables);

        $updates = array();
        foreach ($thing->getData() as $key => $value) {
            $key = trim($key, "`");
            if (is_object($value) || is_array($value)) {
                $value = JsonPrettyPrinter::Json($value);
            }
            $value_slashed = addslashes($value);
            if ($value === null) {
                $updates[] = "`$key` = NULL";
            } else {
                $updates[] = "`$key` = \"$value_slashed\"";
            }
        }
        $selector = "INSERT INTO {$table->getName()} ";
        $data = "SET " . implode(", ", $updates);

        $query = "{$selector}\n{$data}";

        $this->query($query);

        $insertId = $this->lastInsertId();

        return $insertId;
    }
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;
    }
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 . ')'
        );
    }
1136303
public static function sql_prepare($str, $used_in_like = false)
    {
        if (!self::getInstance()->pdo_db) {
            self::getInstance()->connect();
        }

        if (is_array($str)) {
            foreach ($str as &$v) {
                $v = self::sql_prepare($v);
            }
        } else {
            $str = substr(self::getInstance()->pdo_db->quote(trim((string)$str)), 1, -1);

            if ($used_in_like) {
                $str = str_replace(['_', '%'], ['\_', '\%'], $str);
            }
        }

        return $str;
    }
840541
public function generateNewPDO() :\PDO
    {
        if($this->validateConfig()) {
            $dns = $this->driver . ':dbname=' . $this->database . ";host=" . $this->host;
            return new \PDO($dns, $this->user, $this->pass);
        }
        else {
            throw (new \Exception("Invalid or missing database connection parameters"));
        }
    }
268341
private function prepare(string $sql, array $params = []): \PDOStatement
    {
        return $this->pdo()->connectionProcess(function (Pdo $pdo) use ($sql, $params) {
            $stmt = $pdo->prepare($sql);

            if ($params) {
                $k = 1;

                foreach ($params as $key => $value) {
                    $stmt->bindValue(is_int($key) ? $k++ : $key, $value);
                }
            }

            $this->fire($sql, $params);

            $stmt->execute();

            $pdo->checkError();

            return $stmt;
        });
    }
486305
public function query($sql, $bind = [], $fetchMode = \PDO::FETCH_ASSOC, $useMaster = false)
    {
        $sql = $this->_replaceQuoteCharacters($sql);

        try {
            $statement = $bind ? $this->_execute($sql, $bind) : @$this->_getPdo()->query($sql);
        } catch (\PDOException $e) {
            $failed = true;

            if ($this->_transaction_level === 0 && !$this->_ping()) {
                try {
                    $this->close();
                    $statement = $bind ? $this->_execute($sql, $bind) : @$this->_getPdo()->query($sql);
                    $failed = false;
                } catch (\PDOException $e) {

                }
            }

            if ($failed) {
                throw new DbException([
                    ':message => ' . PHP_EOL . 'SQL: ":sql"' . PHP_EOL . ' BIND: :bind',
                    'message' => $e->getMessage(),
                    'sql' => $sql,
                    'bind' => json_encode($bind, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
                ], 0, $e);
            }
        }

        return $statement->fetchAll($fetchMode);
    }
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;
    }
202620
function givePdo(\PDO $conn)
    {
        if ($this->pdo)
            throw new exImmutable;


        $this->pdo = $conn;
        return $this;
    }
423015
function prepareSqlQuery( &$fd, &$buffer )
    {

        $sqlQueryArray = array();
        while( count( $sqlQueryArray ) == 0 && !feof( $fd ) )
        {
            $buffer  .= fread( $fd, 4096 );
            if ( $buffer )
            {
                // Fix SQL file by deleting all comments and newlines
                // eZDebug::writeDebug( $buffer, "read data" );
                $sqlQuery = preg_replace( array( "/^#.*\n" . "/m",
                                                 "#^/\*.*\*/\n" . "#m",
                                                 "/^--.*\n" . "/m",
                                                 "/\n|\r\n|\r/m" ),
                                          array( "",
                                                 "",
                                                 "",
                                                 "\n" ),
                                          $buffer );
//            eZDebug::writeDebug( $sqlQuery, "read data" );

                // Split the query into an array
                $sqlQueryArray = preg_split( "/;\n/m", $sqlQuery );

                if ( preg_match( '/;\n/m', $sqlQueryArray[ count( $sqlQueryArray ) -1 ] ) )
                {
                    $buffer = '';
                }
                else
                {
                    $buffer = $sqlQueryArray[ count( $sqlQueryArray ) -1 ];
                    array_splice( $sqlQueryArray, count( $sqlQueryArray ) -1 , 1 );
                }
            }
            else
            {
                return $sqlQueryArray;

            }
        }
        return $sqlQueryArray;
    }
831668
private function tryConnect(): void
    {
        $config = $this->getConfig();

        $pdoConfig = [
          PDO::ATTR_EMULATE_PREPARES => false,
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false,
          PDO::ATTR_PERSISTENT => $config['persistent'] ?? true,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ];

        if (isset($config['adapter_options'])) {
            foreach ($config['adapter_options'] as $key => $value) {
                $pdoConfig[$key] = $value;
            }
        }

        $charset = $config['charset'] ?? 'utf8';

        if (!isset($config['socket'])) {
            // not a socket
            $port = $config['port'] ?? 3306;

            $this->pdo = new PDO("mysql:host={$config['host']};port={$port};dbname={$config['database']};charset={$charset}", $config['username'], $config['password'], $pdoConfig);
        } else {
            // the case with unix_socket
            $this->pdo = new PDO("mysql:unix_socket={$config['socket']};dbname={$config['database']};charset={$charset}", $config['username'], $config['password'], $pdoConfig);
        }
    }
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;
	}
166561
public function prepareQuery(string $sql, array $data): ?PDOStatement
	{
		// Prepare the sql, save the statement for easy access later
		$this->statement = $this->prepare($sql);

		// Bind the parameters
		foreach($data as $k => $value)
		{
			// Parameters are 1-based, the data is 0-based
			// So, if the key is numeric, add 1
			if(is_numeric($k))
			{
				$k++;
			}
			$this->statement->bindValue($k, $value);
		}

		return $this->statement;
	}
1289652
static function PDO(\PDO $pdo):self{
    return new class($host, $port) implements \ArrayAccess{

      function __construct(string $host, int $port){

      }

      function offsetExists($uri){

      }

      function offsetGet($uri):\ArrayAccess{
        return new class($uri) extends \Exception implements \ArrayAccess{#{{{

        };#}}}
      }

      function offsetSet($uri, $value){

      }

      function offsetUnset($uri){

      }

    };
  }
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;
    }
1264701
protected function send()
    {
//      reset of these properties each time when the database was queried
        $this->reset();

        $this->stmt = $this->pdo->prepare($this->query);
        if (! $this->stmt->execute($this->params)) {
            $this->setError(true);
        }
    }
686312
public function prepare(string $sql, array $params = []): Statement
    {
        if (!$stmt = $this->connection->prepare($sql)) {
            $error = [
                'error' => $this->connection->error,
                'errno' => $this->connection->errno,
                'sqlstate' => $this->connection->sqlstate
            ];

            throw new SqlException('Failed to prepare statement', [$error], $sql, $params);
        }

        if (!empty($params)) {
            if (!$stmt->bind_param(self::getMysqlParamTypes($params), ...$params)) {
                throw new SqlException('Failed to bind params', $stmt->error_list, $sql, $params);
            }
        }

        return new Statement($stmt, $this->usedPrepare, $sql, $params);
    }