Search code examples
phpclassload

PHP Class - How to connect to the database only once


I tried to do a simple SQL class. There is just one problem:

function __classDBREAD($table, $where, $value, $back)
{
    $link = mysql_connect('127.0.0.1','XXXX','XXXXXX');
    mysql_select_db('XXXX', $link);
    mysql_set_charset('utf8');

    $sql = "SELECT * FROM $table WHERE $where = '$value' LIMIT 1";
    $result = mysql_query($sql, $link) or die(mysql_error());
    $row = mysql_fetch_assoc($result);
    return $row[$back];
    mysql_close($link);
}

Now, how can I connect to the SQL only once and add functions like "dbUpdate", "dbInsert" and "dbRead" without connecting to the database every time?

The same for the teamspeak connection.

Here an example:

require_once                      ("lib/TeamSpeak3/TeamSpeak3.php");
    $ts3_VirtualServer              = TeamSpeak3::factory("serverquery://XXXXX:[email protected]:10011/?server_port=XXXX");
    $__varTeamspeakClients          = $ts3_VirtualServer->clientList();
    $__intTeamspeakClientsOnline    = $ts3_VirtualServer["virtualserver_clientsonline"] - 1;
    $ts3_VirtualServer->request('clientupdate client_nickname='.$this->__classRndString(8));

The same problem. How to define the connection only once, when I include the Class to the page?


Solution

  • First of all, you should not be using the mysql_* functions at all. They're deprecated and dangerous to use. Buth hypthetically, you could use globals.

    Define your connection outside of the function (in the global scope) then use global to give your function acces to it. Now all you have to do is include that one "global" line in all your functions that need it.

    $link = mysql_connect('127.0.0.1','XXXX','XXXXXX');
    
    function __classDBREAD($table, $where, $value, $back)
    {
        global $link;
        mysql_select_db('XXXX', $link);
        mysql_set_charset('utf8');
    
        $sql = "SELECT * FROM $table WHERE $where = '$value' LIMIT 1";
        $result = mysql_query($sql, $link) or die(mysql_error());
        $row = mysql_fetch_assoc($result);
        return $row[$back];
        mysqli_close($link);
    }
    

    EDIT...

    I didn't read this too closely. I see you're working on a class, so globals is not the best option. Consider this..

    class mydbclassthing {
        private $conn;
        public function __construct(){
            $this->conn = mysql_connect('127.0.0.1','XXXX','XXXXXX');
        }
    
        function __classDBREAD($table, $where, $value, $back)
        {
            $link = $this->con;
            mysql_select_db('XXXX', $link);
            mysql_set_charset('utf8');
    
            $sql = "SELECT * FROM $table WHERE $where = '$value' LIMIT 1";
            $result = mysql_query($sql, $link) or die(mysql_error());
            $row = mysql_fetch_assoc($result);
            return $row[$back];
            mysql_close($link);
        }
    }