sql >> Database teknologi >  >> RDS >> Mysql

Har jeg brug for en php mysql-forbindelse i hver funktion, der bruger database?

For at undgå at oprette en ny databaseforbindelse hver gang, kan vi bruge Singleton designmønster -

vi skal have en databaseklasse- for at håndtere DB-forbindelsen-

Database.class.php

<?php
        class Database
        {
            // Store the single instance of Database
            private static $m_pInstance;

            private $db_host='localhost';
            private $db_user = 'root';
            private $db_pass = '';
            private $db_name = 'databasename';

            // Private constructor to limit object instantiation to within the class
            private function __construct() 
            {
                mysql_connect($this->db_host,$this->db_user,$this->db_pass);
                mysql_select_db($this->db_name);
            }

            // Getter method for creating/returning the single instance of this class
            public static function getInstance()
            {
                if (!self::$m_pInstance)
                {
                    self::$m_pInstance = new Database();
                }
                return self::$m_pInstance;
            }

            public function query($query)
            {
               return mysql_query($query);
            }

         }
?>

&vi kan kalde det fra andre filer-

other.php

<?php
       include 'singleton.php';
       $pDatabase = Database::getInstance();

       $result = $pDatabase->query('...');
?>


  1. Codeception-accepttest inden for databasetransaktion på MySQL

  2. Erstat i forespørgselssyntaks

  3. Er det en god idé at bruge MySQL og Neo4j sammen?

  4. Sådan fungerer Cos() i PostgreSQL