1

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?

NiGhTHawK
  • 838
  • 1
  • 9
  • 14
Chan
  • 1,947
  • 6
  • 25
  • 37
  • You have two solutions. Make dbclass as singleton or extend all of you classes from db class. Also you would want to move connect call into constructor of db class and stop calling connect from outside. You just make sql queries and handle connection inside dbclass. I dont actually think if this is necessary but this is the way. – makallio85 Jan 14 '14 at 05:13
  • Singleton is the key solution here. – makallio85 Jan 14 '14 at 05:17
  • I am sorry, could you please show me simple samples :) – Chan Jan 14 '14 at 05:32
  • `var` is so PHP4. :P – cHao Jan 14 '14 at 06:31
  • 1
    See this example: http://stackoverflow.com/questions/19302072/how-to-use-singleton-as-connection-in-php-class – makallio85 Jan 14 '14 at 07:11

2 Answers2

1

To solve this issue, You should read the "Design Patter". Specially "Singleton Pattern". Generally this pattern is used when we make such classes.

Basic is, In this pattern,

We can have only one object of that class in whole application at a time.

Read this is simple and very clear example. http://kazymjir.com/blog/singleton-pattern-php-example-tutorial/

developerCK
  • 4,418
  • 3
  • 16
  • 35
0

Try add var $conn = NULL; in the parent class.

This explicitly declare it as a public variable and can be inherited.

msg7086
  • 461
  • 2
  • 11
  • I indeed had it, just forgot to add, sorry about that, the issue is how sub class get `connect` function's result if I already call it before – Chan Jan 14 '14 at 05:14
  • @吳承諺 Either put the variable into class level (make it static and call by `::`), or use `mysql_*` without providing the `connection` as it will use the last connection if not provided. – msg7086 Jan 14 '14 at 05:22
  • I wished, but sometimes weird happens without add connection string – Chan Jan 14 '14 at 05:29