<?php
include_once ("_dirinfo.php");
include_once (PATH_TO_ROOT."init.php");

/**
 * executes statements, generated on client to save data from questionaries
 *
 */
class sqlFileTransaction
{
	var $errorMessage="";
	var $iserror;
	var $sqlfile;
	var $srv_db;
	
	/**
	 * set main parameter 
	 *
	 * @param string $sqlf path of the sql file
	 * @param db $connection database connection, taken from init.php
	 */
	function __construct($sqlf, $connection){
		$this->errorMessage = "ok";
		$this->iserror=0;
		$this->sqlfile = $sqlf;
		$this->srv_db = $connection;
	}
	
	/**
	 * executes statements from sql file
	 *
	 */
	function doQuery() {
		$ok = true;
		$count = 0;
		$j = 0;
		if (file_exists ( $this->sqlfile )) {
			$handle = fopen ( $this->sqlfile, "r" );
			//fopen ( $this->sqlfile, "r" );
			while ( ! feof ( $handle ) ) {
				$sql [$j] = fgets ( $handle ); //fill array with lines from sql file - statements
				$j ++;
			}
			fclose ( $handle );
			$ok = true;
			foreach ( $sql as $value ) {
				$count++;
				if (strlen($value) > 5)//check, if there are any empty lines, ignore them
					$this->srv_db->SQLexecute ( $value );					
				if ($this->srv_db->IsError ()) {
					$ok = false;
					break;
				}
			}
			if ($ok) {//if all was ok, delete sql file
				unlink ( $this->sqlfile );
			} else {
				$this->errorMessage = "Line in SqlFile: ".$count." SQL error: ".$this->srv_db->GetError();
				$this->iserror = 1;
			}
		}
		else
		{
			$this->errorMessage = "Can not find sql file.";
		}
	}
	function getError (){return $this->errorMessage;}
	
	function isError(){ return $this->iserror;}
}
?>