dev.base86 and blog software © 2008 R. Schoo. All other copyrights are property of their respective owners.
Proudly powered by the lightweight MooTools JavaScript framework. Icons by FamFamFam.
I'm using a database class for a while now, and I must say it works fantastic. It facilitates in my PHP/MySQL development by aiding in debugging and error reporting. DbConnect will automatically close the connection when the page thread is finished. The class is PHP 4 proof.
Example use:
//Open connection$dbConnection = new dbConnect();
//Send a MySQL query$dbConnection->query("SELECT * FROM table");
//Fetch a row$row = $dbConnection->fetchRow();
//Loop through all rowswhile($row = $dbConnection->fetchRow()) { }
//If you know the query will return 1 record, fetch the cell via$value = $dbConnection->fetchFirstCell();
$result = $dbConnection->result; //Return the complete result
$count = $dbConnection->affectedRows; //Return the affected rows count in previous MySQL operation
$id = $dbConnection->insertID; //Return the ID generated from the previous INSERT operation
Read more for the complete class.
Class dbConnect:
class dbConnect {
var $connection;
var $result;
var $affectedRows;
var $insertID;
function dbConnect() {
$this->connection = mysql_connect(db_host, db_user, db_pass);
mysql_select_db(db_name);
register_shutdown_function(array(&$this, "close"));
}function close() {
mysql_close($this->connection);
}function query($query, $debug = false) {
$this->result = mysql_query($query) or die();
$this->affectedRows = mysql_affected_rows();
$this->insertID = mysql_insert_id();
if($debug) {
echo "<fieldset><legend>SQL-Query in <i>".$_SERVER["SCRIPT_NAME"]."</i></legend>".PMA_SQP_formatHtml(PMA_SQP_parse($query))."</fieldset>";
if(eregi("select", $query)) {
echo "<fieldset><legend>SELECT result: ".$this->affectedRows." row(s)</legend><table cellspacing="0">";
for($i = 0; $row = $this->fetchRow("assoc", $this->result); $i++) {
if($i == 0) {
echo "<tr>";
foreach($row as $key => $value) echo "<th>$key</th>";
echo "</tr>";
}echo "<tr>";
foreach($row as $value) echo "<td>$value</td>";
echo "</tr>";
}echo "</table></fieldset>";
} } }function fetchFirstCell() {
$row = mysql_fetch_row($this->result);
return $row[0];
}function fetchRow($type = "assoc", $result = null, $debug = false) {
switch($type){
case "assoc":
return mysql_fetch_array(($result ? $result : $this->result), MYSQL_ASSOC);
break;case "num":
return mysql_fetch_array(($result ? $result : $this->result), MYSQL_NUM);
break;case "both";
return mysql_fetch_array(($result ? $result : $this->result), MYSQL_BOTH);
break;case "obj":
return mysql_fetch_object($result ? $result : $this->result);
break; } }function freeResult() {
mysql_free_result($this->result);
}}Don't forget to define db_host, db_user, db_pass and db_name in your configuration file.
The PMA_SQP_formatHtml and PMA_SQP_parse are the same functions used in PHPMyAdmin to format a query. I will post these later.