Do I need a php mysql connection in each function that uses database?

前端 未结 5 1116
无人共我
无人共我 2020-12-25 09:33

I am creating a php restful API and currently I have the database connection information in each function.

//Connect To Database
    $hostname=host;
    $use         


        
5条回答
  •  不思量自难忘°
    2020-12-25 09:55

    To avoid creating a new database connection each time, we can use Singleton design pattern-

    we need to have a database class- to handle the DB connection-

    Database.class.php

    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);
                }
    
             }
    ?>
    

    & we can call it from other files-

    other.php

    query('...');
    ?>
    

提交回复
热议问题