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?

5
  • 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. Commented Jan 14, 2014 at 5:13
  • Singleton is the key solution here. Commented Jan 14, 2014 at 5:17
  • I am sorry, could you please show me simple samples :) Commented Jan 14, 2014 at 5:32
  • var is so PHP4. :P Commented Jan 14, 2014 at 6:31
  • 1
    See this example: stackoverflow.com/questions/19302072/… Commented Jan 14, 2014 at 7:11

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Singleton for database logic it's amazing, saves alot of trouble. tho that unit testing sucks :p
0

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

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

3 Comments

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
@吳承諺 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.
I wished, but sometimes weird happens without add connection string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.