Mega Code Archive

 
Categories / Php / MySQL Database
 

Simple database class

<? /* $result = $db->query($query); while ($row = $db->fetch_array($result)) { echo '<a href="'.$row['page_name'].'">'.$row['title'].'</a> - '.$row['description']; } */ class db {// db.class.php, Database connection / query functions. var $hostname;// Hostname that the object should connect to var $username;// Username that the object should use var $password;// Password that the object should use var $database;// Database that the object should use var $query_num;// counts the total queries that the object has done. Some BBs do this. Might be of use for optimization etc function set_cred($hostname,$username,$password) { $this->hostname = $hostname $this->username = $username $this->password = $password } function db_connect() { $result = mysql_connect($this->hostname, $this->username, $this->password); /* Open a persistant connection to the server. Same as mysql_connect with CGI Because PHP has to be spawned each time anyway. */ if (!$result) { echo 'Connection to database server at: '.$this->hostname.' failed.'; return false; } return $result; } function db_pconnect() { $result = mysql_pconnect($this->hostname, $this->username, $this->password); /* Open a persistant connection to the server. Same as mysql_connect with CGI Because PHP has to be spawned each time anyway. */ if (!$result) { echo 'Connection to database server at: '.$this->hostname.' failed.'; return false; } return $result; } function select_db($database) { $this->database = $database; if (!mysql_select_db($this->database)) { echo 'Selection of database: '.$this->database.' failed.'; return false; } } function query($query) { $result = mysql_query($query) or die("Query failed: $query<br><br>" . mysql_error()); return $result; } function fetch_array(&$result) { return mysql_fetch_array($result); } function return_query_num() { return $this->query_num; } function num_rows($result) { return mysql_num_rows($result); } }; /* EXAMPLE: */ $hostname = 'localhost'; $username = 'user'; $password = 'xxxxxxxx'; $database = 'database'; $db->set_cred($hostname,$username,$password)//set credentials ready to connect, $db->db_connect();// connect to the database using a non persistant connection // $db->db_pconnect();// connect to the database using a persistant connection $db->select_db($database); // Select database $query = "SELECT * FROM table"; $result = $db->query($query); // excute query with $result as a handle $numrows = $db->num_rows($result); // Get the number of rows returned or affected while($row = $db->fetch_array) { echo $row[0] . '<br>' . $row['somerow'] . '<br>'; } // echo some data in a loop echo $numrows . 'Returned from ' . $query; /* This class is ideally used for managing multiple database connections more efficiently. It could be modified to work with other databases. It is NOT designed as a more complex database abstraction layer. */ ?>