PHP: Basic PHP Database Class Example

Learning the PHP Class System is one of the most integral parts of becoming a good and efficient programmer. Classes are great because they give you the ability to share them amongst other classes between your project(s), so that you can split up all of your functions into parts. If you are writing an Intranet application with an Employee Database and an Inventory of company parts, you do not really want to mix those functions together in the same file. By using 2 PHP Classes, you can split them up into 2 separate files but then be able to share them by extending them, which will be covered in another tutorial.

In the meantime, here is a perfect basic PHP class that you can copy and paste into your editor and use with all of your projects. Simply fill in the database variables at the top of the script, save it as a .php file, and you are good to go:

class.db.php

<?php 

class DB_Class {
	var $host = "localhost"; //database host
	var $username = ""; //database username
	var $password = ""; //database password
	var $database = ""; //mysql database
	
	
	function query($sql) {
		$this->db = mysql_connect($this->host, $this->username, $this->password);
		 mysql_select_db($this->database, $this->db) or die ("Could not select database");
		  $result = mysql_query($sql, $this->db) or die ("Invalid query: " . mysql_error());
		   return $result;
	}

	function numRows($result) {
		$count = mysql_num_rows($result);
		   return $count;
	}

	function fetch($sql) {
		$this->db = mysql_connect($this->host, $this->username, $this->password);
		 mysql_select_db($this->database, $this->db) or die ("Could not select database");
		  $data = array();
		   $result = $this->query($sql);

		while($row = mysql_fetch_assoc($result)) {
			$data[] = $row;
		}
		   return $data;
	}

}

?>

Leave a Comment

Your email address will not be published. Required fields are marked *