<?

class ps_DB {


  var $lid = 0;             	
  var $qid = 0;			
  var $row;			
  var $record = array();	
  var $error = "";		
  var $errno = "";		
  var $path;


function connect() { 
global $path;

  require ($path . "setup.php");

    if ($this->lid == 0) {
      $this->lid = mysql_pconnect(DB_HOST,DB_USER,DB_PWD); 
      if (!$this->lid) {
	$this->halt("connect(" . DB_HOST . "," . DB_USER . ",PASSWORD)  failed.");
      } 
      
      if (!@mysql_select_db(DB_NAME,$this->lid)) {
	$this->halt("Cannot connect to database ".DB_NAME);
	return 0;
      }
    }
    return $this->lid;
  }


function query($q) {
    
    if (empty($q))
      return 0;
    
    if (!$this->connect()) {
      return 0; 
    }
    
    if ($this->qid) {
      @mysql_free_result($this->qid);
      $this->qid = 0;
    }
    
    $this->qid = @mysql_query($q, $this->lid);
    $this->row   = 0;
    $this->errno = mysql_errno();
    $this->error = mysql_error();
    if (!$this->qid) {
      $this->halt("Invalid SQL: ".$q);
    }

    return $this->qid;
  }
  

function next_record() {

    if (!$this->qid) {
      $this->halt("next_record called with no query pending.");
      return 0;
    }
    
    $this->record = @mysql_fetch_array($this->qid);
    $this->row   += 1;
    $this->errno  = mysql_errno();
    $this->error  = mysql_error();
    
    $stat = is_array($this->record);
    return $stat;
  }
  

function f($field_name) {
    return stripslashes($this->record[$field_name]);
  }

 function sf($field_name) {
    global $vars, $default;

    if ($vars["error"] and $vars["$field_name"]) {
      return stripslashes($vars["$field_name"]);
    } elseif ($default["$field_name"]) {
      return stripslashes($default["$field_name"]);
    } else {
      return stripslashes($this->record[$field_name]);
    }
  }                             


  function p($field_name) {
      print stripslashes($this->record[$field_name]);
  }                             
  function sp($field_name) {
    global $vars, $default;

    if ($vars["error"] and $vars["$field_name"]) {
      print stripslashes($vars["$field_name"]);
    } elseif ($default["$field_name"]) {
      print stripslashes($default["$field_name"]);
    } else {
      print stripslashes($this->record[$field_name]);
    }
  }                          


  function num_rows() { 
    
    if ($this->lid) { 
      return @mysql_numrows($this->qid); 
    } 
    else { 
      return 0; 
    } 
  }



  

  function halt($msg) {
    $this->error = @mysql_error($this->lid);
    $this->errno = @mysql_errno($this->lid);

    printf("</td></tr></table><b>Database error:</b> %s<br>\n", $msg);
    printf("<b>MySQL Error</b>: %s (%s)<br>\n",
	   $this->errno,
	   $this->error);
    
    exit;

  }

}
?>
