简体   繁体   English

在每个使用数据库的函数中我都需要一个 php mysql 连接吗?

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

I am creating a php restful API and currently I have the database connection information in each function.我正在创建一个 php restful API,目前我在每个函数中都有数据库连接信息。

//Connect To Database
    $hostname=host;
    $username=username;
    $password=password;
    $dbname=dbname;

    mysql_connect($hostname, $username, $password) OR DIE('Unable to connect to database! Please try again later.');
    mysql_select_db($dbname);
mysql_query($sqlApiAccess) or die('Error, insert query failed');

What is the best way of doing this, Can I have one database connection per php file?这样做的最佳方法是什么,我可以为每个 php 文件建立一个数据库连接吗? Or do I need to do it per function that uses the database.或者我是否需要为每个使用数据库的函数执行此操作。

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数据库.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);
            }

         }
?>

& we can call it from other files- &我们可以从其他文件中调用它-

other.php其他.php

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

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

Create a config.php And add the code:创建一个 config.php 并添加代码:

config.php:

$hostname = 'host';
$username = 'username';
$password = 'password';
$dbname   = 'dbname';

$conn = mysqli_connect($hostname, $username, $password) OR die('Unable to connect to database! Please try again later.');
mysqli_select_db($conn, $dbname);

Then in any file you wish to use mysql, add the following:然后在您希望使用 mysql 的任何文件中,添加以下内容:

script2.php

<?php
require_once 'config.php';

mysqli_query($sqlApiAccess) or die('Error, insert query failed');
?>

There is no need to make connection in each function.无需在每个功能中进行连接。 you need to make a connection file like conn.php and make the connection queries.您需要创建一个像conn.php这样的连接文件并进行连接查询。

<?php
mysql_connect("localhost", "admin", "1admin") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
?>

in any other file where you want to connect database just write this line在要连接数据库的任何其他文件中,只需写下这一行

<?php include("conn.php");?> 

On this file you are able to run any query.在此文件上,您可以运行任何查询。

do this:做这个:

$db_connection= mysql_connect($hostname, $username, $password) OR DIE('Unable to connect to database! Please try again later.');

And every time you want to query:每次您要查询时:

mysql_query("my_query",$db_connection);

Note, if you connect to the DB in a function, you will need to global $db_connection .请注意,如果您在函数中连接到数据库,则需要全局$db_connection

And when you want to close the DB connection:当你想关闭数据库连接时:

mysql_close($db_connection);

Why won't you move out the connection information into config and the call to mysql_connect into some factory?你为什么不把连接信息移到 config 并将对mysql_connect的调用移到某个工厂?

Eg例如

class ConnectionFactory {
    public static MysqlConnection CreateConnection() {
        $connection = mysql_connect(Config::$host, Config::$port etc);
        mysql_select_db($connection, Config::$schema);
        return $connection;
    }
}

and then in your code然后在你的代码中

$connection = ConnectionFactory::CreateConnection();
mysql_query($connection, $sqlApiAccess) or die('Error, insert query failed');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM