<?php

/**
 * Object executes sql queries
 *
 * @author: http://phpdao.com
 * @date: 27.11.2007
 */
class QueryExecutor {

    /**
     * Wykonaniew zapytania do bazy
     *
     * @param sqlQuery obiekt typu SqlQuery
     * @return wynik zapytania
     */
    public static function execute($sqlQuery) {

        $transaction = Transaction::getCurrentTransaction();
        if (!$transaction) {
            $connection = new Connection();
        } else {
            $connection = $transaction->getConnection();
        }
        $query = $sqlQuery->getQuery();
        $result = $connection->executeQuery($query);
        if (!$result) {
            throw new Exception(mysqli_error());
        }
        $i = 0;
        $tab = array();
        while ($row = mysqli_fetch_array($result)) {
            $tab[$i++] = $row;
        }
        //mysql_free_result($result);
        mysqli_free_result($result);
        if (!$transaction) {
            $connection->close();
        }
        return $tab;

        //  echo $sqlQuery;
    }

    public static function executeUpdate($sqlQuery, $multiQuery = 0) {

        $transaction = Transaction::getCurrentTransaction();
        if (!$transaction) {
            $connection = new Connection();
        } else {
            $connection = $transaction->getConnection();
        }
        $query = $sqlQuery->getQuery();


        $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
        $txt = $query . ";\r\n";
        fwrite($myfile, $txt);

        fclose($myfile);
        if ($multiQuery == 0) {
            $result = $connection->executeQuery($query);
            if (!$result && $_SESSION['stop_checking_result'] != 1) {
                throw new Exception(mysqli_error());
            }
        } else {
            $result = $connection->executeMultiQuery($query);
        }

        $affected_rows = $_SESSION['affected_rows'];
        unset($_SESSION['affected_rows']);
        return $affected_rows; //mysqli_affected_rows($connection);
    }

    public static function executeInsert($sqlQuery) {
        QueryExecutor::executeUpdate($sqlQuery);
        $id = $_SESSION['inserted_id'];
        unset($_SESSION['inserted_id']);
        return $id; //mysqli_insert_id(ConnectionFactory::getConnection());
    }

    /**
     * Wykonaniew zapytania do bazy
     *
     * @param sqlQuery obiekt typu SqlQuery
     * @return wynik zapytania
     */
    public static function queryForString($sqlQuery) {
        $transaction = Transaction::getCurrentTransaction();
        if (!$transaction) {
            $connection = new Connection();
        } else {
            $connection = $transaction->getConnection();
        }
        $result = $connection->executeQuery($sqlQuery->getQuery());
        if (!$result) {
            throw new Exception(mysqli_error());
        }
        $row = mysqli_fetch_array($result);
        return $row[0];
    }

}

?>