config.php
<?php
define('DB_HOST', 'localhost');
define('DB_DB', 'db');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '123456');
class.main.php
<?php
class main {
var $host = '';
var $db = '';
var $username = '';
var $password = '';
var $conn = '';
public function __construct() {
$this->host = DB_HOST;
$this->db = DB_DB;
$this->username = DB_USERNAME;
$this->password = DB_PASSWORD;
}
/**
* Connect to database
*/
function connect() {
$this->conn = mysql_connect($this->host, $this->username, $this->password) or trigger_error(mysql_error(), E_USER_ERROR);
mysql_query("SET NAMES 'utf8'");
}
public function myRow($sql) {
mysql_select_db($this->db, $this->conn);
$rec = mysql_query($sql, $this->conn) or die(mysql_error());
$row = mysql_fetch_assoc($rec);
$count = mysql_num_fields($rec);
if ($this->recordCount > 0) {
$result = array();
$temp = array();
do {
for ($i = 0; $i < $count; $i++) {
$name = mysql_field_name($rec, $i);
$temp[$name] = $row[$name];
}
array_push($result, $temp);
} while($row = mysql_fetch_assoc($rec));
} else {
$result = NULL;
}
mysql_free_result($rec);
return $result;
}
}
This a part of my class, if I want to get data, it's like
<?php
include 'config.php';
include 'class.main.php';
$main = new main;
$main->connect();
$sql = 'SELECT * FROM table';
$row = $main->myRow($sql);
Sometimes I will make other class for different case, some of the class might need to use myRow
function, this is how I did now.
class.sub.php
<?php
class sub extends main {
public function __construct() {
parent::__construct();
}
/**
* Get member information
*
* @param integer $id member id
* @return data
*/
public function member($id = NULL) {
$this->connect();
if (NULL === $id) {
$id = $_SESSION['memberId'];
}
$sql = "SELECT *
FROM `members`
WHERE `on` = 1";
return $this->myRow($sql);
}
}
<?php
include 'config.php';
include 'class.main.php';
$main = new main;
include 'class.sub.php';
$sub = new sub;
$main->connect();
$sql = 'SELECT * FROM table';
$row = $main->myRow($sql);
$member = $sub->member();
echo $member['xxx'];
It's work right now, all I concerned is I call $this->connect in member
function again otherwise I can't get the connection from main class, but it means I connect to database twice in one page, it such a resource wasted, how to fix it?