class SystemDatabaseManager
{
  public $file;
  public $db;
  public $query_result;
  public $row_array;
  public $sql;

  public function open($file){
    echo "open";
    $this->file=$file;
    $this->db = sqlite_open($this->file, SQLITE_ASSOC, $sqliteerror);
    return $this->db;
  }

  public function reopen(){
    open($this->file);
  }

  public function close(){
    sqlite_close($this->db);
  }

  public function query($sql){
    $this->sql=$sql;
    //echo($sql);
    $this->query_result=sqlite_query($this->db, $sql);
    //var_dump($this->query_result);echo("->query:".$sql);
    //echo(sqlite_error_string(sqlite_last_error($this->db)) . "\n" . $sql);
    if($this->query_result || sqlite_last_error($this->db)==0)
      return true;

    echo(sqlite_error_string(sqlite_last_error($this->db)) . "\n" . $sql);
    return false;
  }

  public function fetch(){
    //var_dump($this->query_result);
    $this->row_array=sqlite_fetch_array($this->query_result, SQLITE_ASSOC);
    //echo(sqlite_error_string(sqlite_last_error($this->db)) . "\n" . $this->sql);
    if($this->row_array)
    {
      //var_dump($this->row_array);
      return true;
    }
    return false;
  }
  public function sqlite_last_error(){
   return sqlite_error_string(sqlite_last_error($this->db));
  }

  public function get_array_data($field_name){
    //var_dump($this->row_array);
    return $this->row_array[$field_name];
  }

  public function make_insert_into_sql($table_name){
    $first=true;
    foreach($this->row_array as $key=>$val) {
      if(!$first)
      {
        $fields.=",";
        $values.=",";
      }
      $fields.=$key;
      $values.="'$val'";
      $first=false;
    }
    
    $sql="INSERT INTO $table_name($fields)VALUES($values);";
    
    return $sql;
  }

  public function update_table_by_another($a,$b,$where,$update){
    $sql="SELECT * FROM $a;";
    $a_result=sqlite_query($this->db, $sql);
    //echo($sql);
    while($a_row=sqlite_fetch_array($a_result))
    {
      $where_string=$a_row[$where];
      $sql="SELECT * FROM $b WHERE $where='$where_string'";
      //echo($sql);
      $b_result=sqlite_query($this->db, $sql);
      $b_row=sqlite_fetch_array($b_result, SQLITE_ASSOC);
      if($b_row)
      {
        $update_new_val=$b_row[$update];
        
        //update new value
        $sql="UPDATE $a set $update=$update_new_val WHERE $where='$where_string'";
        //echo($sql."\n");
        sqlite_query($this->db, $sql);
        
        if(sqlite_last_error($this->db)>0)
        {
          echo(sqlite_error_string(sqlite_last_error($this->db)) . "\n" . $sql);
          return false;
        }
      }
    }

    return true;
  }
}
echo "aaaaaaa";
