Database query from class object with php

My question is:

Can I make a request from within such an object:

$result = mysql_query ($q,$dbc) 
          or 
          trigger_error("Query: $q\n<br />MySQL Fout: " . mysql_error($dbc));

by passing the global variable dbconnection $ dbc to the constructor

or is there a better way?

Or creating a singleton class for data binding, but I see a lot of negativity that people write about it.

I am new to creating objects, so I don’t know if I can do it all a little different, with db I mean.

thanks Richard

+3
source share
5 answers

, DB, Zend Framework.

, .

, Zend_Db , .

globals - , ! , , google.

db- Zend Framework - ,

$db = Zend_Db::factory('Pdo_Mysql', array(
'host'     => '127.0.0.1',
'username' => 'webuser',
'password' => 'xxxxxxxx',
'dbname'   => 'test'

));

. , select statement .

, Zend Framework , , .

Zend Framework , , ORM, Doctrine, . , ORM Zend Framework , , , .

+1

, .

IMHO , .

0

:

class DB {
    private $dbc;

    public function __construct($dbConn) {
        $this->dbc = $dbConn;
    }

    public function runQuery() {
        mysql_query($query, $this->dbc);
    }
}
0

. - - , . , .

0

singleton, .

, singleton , , , - . , - . , , , , . .

Singleton, :

 class datbasebase
   {
    static $class = false;
    static function get_connection()
    {
        if(self::$class == false)
        {
            self::$class = new database;
        }
        else
        {
            return self::$class;
        }
    }
    // This will ensure it cannot be created again.
    protected function __construct()
    {
                $this->connection = mysql_connect();
    }
        public function query($query)
        {
                return mysql_query($query, $this->connection;
        }
   }

   $object = database::get_connection();

, , - , . , , .

0

Source: https://habr.com/ru/post/1713524/


All Articles