/* ** The constrcutor, terminates the script if the connection fails ** @params: ** string $server - the server IP or hostname ** string $user - the username ** string $pass - the password ** string $db - the name of the database to use */
/* ** A method which connects to the server. This cannot be called statically. ** @return: boolean */ function connect() { if($this->link=mysql_connect($this->server,$this->user,$this->pass,true)) if(mysql_select_db($this->db,$this->link)) returntrue; if(is_resource($this->link)) print("<div class=\"error-box\">".mysql_error($this->link)."</div>"); returnfalse; }
/* ** Queries the DB ** @param: ** string $query - the SQL query ** boolean $debug - terminates on failure if set to true ** @return: boolean - true if successful, else false */ function query($query,$debug=false) { if($debug) { $this->result=mysql_query($query,$this->link) or die("<div class=\"error-box\">".mysql_error($this->link)."$query</div>"); } else { if($this->result=mysql_query($query,$this->link)) returntrue; returnfalse; }
}
/* ** Fetches rows from the resultset ** @param: ** PHP Constant $type - MYSQL_NUM (default) / MYSQL_ASSOC */ function fetch_rows($type=MYSQL_NUM) { returnmysql_fetch_array($this->result,$type); }
/* ** Returns the no. of rows returned */ function num_rows() { returnmysql_num_rows($this->result); }
/* ** Frees the memory of the resultset */ function free_r() { mysql_free_result($this->result); }
/* ** Returns the last insert ID, for an auto_increment field */ function insert_id() { returnmysql_insert_id($this->link); }
/* ** Closes the MySQL connecttion */ function close() { mysql_close($this->link); } }
The example usage:
Code: PHP
$db = new DB("server.com","admin","pass","customer_db"); $sql = "SELECT * FROM customers"; $db->query($sql); // Number of rows returned printf("The number of rows returned = %d \n<br/>",$db->num_rows());