Should I continue reconnecting to mysql in PHP?

I have a rather large site, and each page is built from several included files, my site is 100% in a procedural format, and I'm trying to learn how to use classes and a more OOP approach in PHP.

Currently my site has a header file that is included in each page, a mysql connection is created in this header and the page lasts, so if I need to run 10 different requests from different files, they all start without the need to create a new connection, so the connection performed only once.

Now, when I try to convert to an OO path, I start writing a mysql class to connect and run queries, so I think about using __construct functions to connect to mysql, I'm just curious how this will work, every time the called class will called, it will make or try to establish a connection to mysql instead of once.

Perhaps I do not understand this clearly. Should I just initiate this class in the header 1 time, and then I don’t have to worry anymore?

+5
source share
6 answers

You can create one global object of your MySQL class and use this object everywhere. Then your constructor will be called only once.

MySQL . mysql_connect , :

mysql_connect() , , .

+6

, -, mysql . , , .

:

class db 
{

    public $host;
    public $user;
    public $pass;
    public $database;

    private static $instance = false;

    private function __construct() 
    {

    }

    public static function getInstance()
    {
        if (self::$instance === false)
        {
            self::$instance = new db;
        }
        return self::$instance;
    }

        public function db_connect()
        {
        }

        public function db_disconnect()
        {
        }
}

, , : db:: getInstance() → db_connect(), , .

+2

, . , , . .

, , , , (Zend_Db ..).

+1

STATIC , . PHP , .

, , PHP 5 PDO.

<?php
// Class providing generic data access functionality
class DatabaseHandler
{
  // Hold an instance of the PDO class
  private static $_mHandler;

  // Private constructor to prevent direct creation of object
  private function __construct()
  {
  }

  // Return an initialized database handler 
  private static function GetHandler()
  {
    // Create a database connection only if one doesn’t already exist
    if (!isset(self::$_mHandler))
    {
      // Execute code catching potential exceptions
      try
      {
        // Create a new PDO class instance
        self::$_mHandler =
          new PDO(PDO_DSN, DB_USERNAME, DB_PASSWORD);

        // Configure PDO to throw exceptions
        self::$_mHandler->setAttribute(PDO::ATTR_ERRMODE,
                                       PDO::ERRMODE_EXCEPTION);
        self::$_mHandler->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
      }
      catch (PDOException $e)
      {
        // Close the database handler and trigger an error
        self::Close();
        trigger_error($e->getMessage(), E_USER_ERROR);
      }
    }

    // Return the database handler
    return self::$_mHandler;
  }
  // Clear the PDO class instance
  public static function Close()
  {
    self::$_mHandler = null;
  }
  // Wrapper method for PDO::prepare
  private static function Prepare($queryString)
  {
    // Execute code catching potential exceptions
    try
    {
      // Get the database handler and prepare the query
      $database_handler = self::GetHandler();
      $statement_handler = $database_handler->prepare($queryString);

      // Return the prepared statement
      return $statement_handler;
    }
    catch (PDOException $e)
    {
      // Close the database handler and trigger an error
      self::Close();
      trigger_error($e->getMessage(), E_USER_ERROR);
    }
  }

  // Wrapper method for PDOStatement::execute()
  public static function Execute($sqlQuery, $params = null)
  {
    // Try to execute an SQL query or a stored procedure
    try
    {
        $statement_handler = self::Prepare($sqlQuery);

      // Execute query
      $statement_handler->execute($params);
    }
    // Trigger an error if an exception was thrown when executing the SQL query
    catch(PDOException $e)
    {
      // Close the database handler and trigger an error
      self::Close();
      trigger_error($e->getMessage(), E_USER_ERROR);
    }
  }

  // Wrapper method for PDOStatement::fetchAll()
  public static function GetAll($sqlQuery, $params = null,
                                $fetchStyle = PDO::FETCH_ASSOC)
  {
    // Initialize the return value to null
    $result = null;

    // Try to execute an SQL query or a stored procedure
    try
    {
        $statement_handler = self::Prepare($sqlQuery);

      // Execute the query
      $statement_handler->execute($params);

      // Fetch result
      $result = $statement_handler->fetchAll($fetchStyle);
    }
    // Trigger an error if an exception was thrown when executing the SQL query
    catch(PDOException $e)
    {
      // Close the database handler and trigger an error
      self::Close();
      trigger_error($e->getMessage(), E_USER_ERROR);
    }

    // Return the query results
    return $result;
  }

  // Wrapper method for PDOStatement::fetch()
  public static function GetRow($sqlQuery, $params = null,
                                $fetchStyle = PDO::FETCH_ASSOC)
  {
    // Initialize the return value to null
    $result = null;

    // Try to execute an SQL query or a stored procedure
    try
    {

      $statement_handler = self::Prepare($sqlQuery);

      // Execute the query
      $statement_handler->execute($params);

      // Fetch result
      $result = $statement_handler->fetch($fetchStyle);
    }
    // Trigger an error if an exception was thrown when executing the SQL query
    catch(PDOException $e)
    {
      // Close the database handler and trigger an error
      self::Close();
      trigger_error($e->getMessage(), E_USER_ERROR);
    }

    // Return the query results
    return $result;
  }

  // Return the first column value from a row
  public static function GetOne($sqlQuery, $params = null)
  {
    // Initialize the return value to null    
    $result = null;

    // Try to execute an SQL query or a stored procedure
    try
    {
        $statement_handler = self::Prepare($sqlQuery);

      // Execute the query
      $statement_handler->execute($params);

      // Fetch result
      $result = $statement_handler->fetch(PDO::FETCH_NUM);

      /* Save the first value of the result set (first column of the first row)
         to $result */
      $result = $result[0];
    }
    // Trigger an error if an exception was thrown when executing the SQL query
    catch(PDOException $e)
    {
      // Close the database handler and trigger an error
      self::Close();
      trigger_error($e->getMessage(), E_USER_ERROR);
    }

    // Return the query results
    return $result;
  }
}
?>
0

(, PDO) , , , , , -.

, , mysql_connect , , . PDO.

0

, mysql_pconnect(), , mysql, .

Alternatively, if you are considering or not using instances in php, you can directly call the php database object, for example:

class DB {}

DB::connect($host, $user, $pass);

If you use this method, you do not need to worry about multiple connections. Of course, if you need to use several connections to several databases at the same time, you can use object instances or create your own class so that it can take several parameters and store them at once (not really recommending this)

-2
source

All Articles