<?php

/**
 * Object represents connection to database
 *
 * @author: http://phpdao.com
 * @date: 27.11.2007
 */
class Connection {

    private $connection;

    public function __construct() {
        $this->connection = ConnectionFactory::getConnection();
    }

    public function close() {
        ConnectionFactory::close($this->connection);
    }

    /**
     * Wykonanie zapytania sql na biezacym polaczeniu
     *
     * @param sql zapytanie sql
     * @return wynik zapytania
     */
    public function executeQuery($sql) {
        //return mysql_query($sql, $this->connection);

        $res = mysqli_query($this->connection, $sql);
//        if (!$res) {
//            echo ("Could not insert data : " . mysqli_error($this->connection));
////            //Could not insert data : Lock wait timeout exceeded; try restarting transaction
//        }
        $_SESSION['inserted_id'] = mysqli_insert_id($this->connection); //$this->connection->insert_id
        $_SESSION['affected_rows'] = mysqli_affected_rows($this->connection);
        return $res;
    }

    /**
     * fatma
     *
     * @param sql zapytanie sql
     * @return wynik zapytania
     */
    public function executeMultiQuery($sql) {
        $res = array();
        $i = 0;
        // Execute multi query
        if (mysqli_multi_query($this->connection, $sql)) {
            do {
                if (mysqli_affected_rows($this->connection) == -1) {//it is select save results
                    // Store first result set
                    if ($result = mysqli_store_result($this->connection)) {
//                    $res[$i] = $result;
                        $allRows = array();
                        while ($row = mysqli_fetch_assoc($result)) {//mysqli_fetch_field
                            array_push($allRows, $row);
                        }
                        $res[$i] = $allRows;
                        mysqli_free_result($result);
                    }
                } else {//it is update or delete save affected rows
                    $res[$i] = mysqli_affected_rows($this->connection);
                }

                $i++;
                //Prepare next result set
            } while (mysqli_more_results($this->connection) && mysqli_next_result($this->connection));
        } else {
            if ($mysqli_error = mysqli_error($this->connection)) {  // check & declare variable in same step to avoid duplicate func call
                //echo "<div style=\"color:red;\"> Query = ", explode(';', $sql)[$i], ", Syntax Error = $mysqli_error</div>";
                throw new Exception($mysqli_error . " , Query = " . explode(';', $sql)[$i]);
            } else {
                echo "error !!!";
            }
        }
        //print_r($res);
        return $res;
    }

}

?>