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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10208691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:39:14  来源:igfitidea点击:

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

phpmysql

提问by Moltra

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? Or do I need to do it per function that uses the database.

这样做的最佳方法是什么,我可以为每个 php 文件建立一个数据库连接吗?或者我是否需要为每个使用数据库的函数执行此操作。

回答by Avisek Chakraborty

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('...');
?>

回答by Menztrual

Create a config.php And add the code:

创建一个 config.php 并添加代码:

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

script2.php

<?php
require_once 'config.php';

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

回答by Waheed Ur Rehman

There is no need to make connection in each function. you need to make a connection file like conn.phpand 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.

在此文件上,您可以运行任何查询。

回答by Waheed Ur Rehman

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

回答by penartur

Why won't you move out the connection information into config and the call to mysql_connectinto some factory?

为什么不将连接信息移出到配置中并将调用mysql_connect移到某个工厂中?

E.g.

例如

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');