PHP-如何让mysqli_connect()返回一个资源,以便与define()一起使用
在PHP中测试不同的MySQL连接方法时,我注意到了一些东西 在PHP中连接数据库时,我通常使用odbc_connect()。我将odbc_connect()返回的resource变量保存为全局常量(使用define()函数),以便在整个应用程序中方便地访问。像这样: 使用odbc_connect()并将返回值保存到常量中可以正常工作:PHP-如何让mysqli_connect()返回一个资源,以便与define()一起使用,php,mysql,global,handle,mysql-connect,Php,Mysql,Global,Handle,Mysql Connect,在PHP中测试不同的MySQL连接方法时,我注意到了一些东西 在PHP中连接数据库时,我通常使用odbc_connect()。我将odbc_connect()返回的resource变量保存为全局常量(使用define()函数),以便在整个应用程序中方便地访问。像这样: 使用odbc_connect()并将返回值保存到常量中可以正常工作: <?php define("_conn", odbc_connect("Driver={MySQL ODBC 5.3 Unicode Driver};Da
<?php
define("_conn", odbc_connect("Driver={MySQL ODBC 5.3 Unicode Driver};Database=MyDB;", "user", "pass"));
?>
<?php
define("_conn", mysql_connect("localhost", "user", "pass", "MyDB"));
?>
将mysql_connect()的返回值(不推荐使用的)保存到常量中也可以正常工作:
<?php
define("_conn", odbc_connect("Driver={MySQL ODBC 5.3 Unicode Driver};Database=MyDB;", "user", "pass"));
?>
<?php
define("_conn", mysql_connect("localhost", "user", "pass", "MyDB"));
?>
但是,尝试将mysqli_connect()的返回值保存到常量中不起作用:
<?php
define("_conn", mysqli_connect("localhost", "user", "pass", "MyDB"));
?>
Warning: Constants may only evaluate to scalar values in C:\...\script.php on line 164
警告:常量只能计算为C:\…\script.php中第164行的标量值
这是不幸的,因为使用mysqli_connect()建立连接并将句柄保存到常量中会很好,而odbc_connect()不可用。我做了研究,发现我可以在MySQL中使用的返回资源的两个数据库连接函数(也可以在define()函数中使用)是odbc_connect()和MySQL_connect()(不推荐使用的一个)。请参阅此链接:
有没有办法让mysqli_connect()返回一个资源,这样我就可以在常量中使用它的返回值(使用define()函数)
PDO也不会返回资源。正如您所看到的,PHP不允许存储
但您仍然可以实现模式或满足您的需要。正如您所看到的,PHP不允许存储
但您仍然可以实现模式或满足您的需要。我建议在这种情况下使用单例模式 这里有一个例子:
<?php
class PDOConnection {
/**
* singleton instance
*
* @var PDOConnection
*/
protected static $_instance = null;
/**
* Returns singleton instance of PDOConnection
*
* @return PDOConnection
*/
public static function instance() {
if ( !isset( self::$_instance ) ) {
self::$_instance = new PDOConnection();
}
return self::$_instance;
}
/**
* Hide constructor, protected so only subclasses and self can use
*/
protected function __construct() {}
function __destruct(){}
/**
* Return a PDO connection using the dsn and credentials provided
*
* @param string $dsn The DSN to the database
* @param string $username Database username
* @param string $password Database password
* @return PDO connection to the database
* @throws PDOException
* @throws Exception
*/
public static function getConnection() {
$dsn = 'mysql:dbname=_____;host=_____';
$username = '_____';
$password = '_____';
$conn = null;
try {
$conn = new \PDO($dsn, $username, $password);
//Set common attributes
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
//TODO: flag to disable errors?
}
catch(Exception $e) {
//TODO: flag to disable errors?
}
}
/** PHP seems to need these stubbed to ensure true singleton **/
public function __clone()
{
return false;
}
public function __wakeup()
{
return false;
}
}
?>
我建议在这种情况下使用单例模式 这里有一个例子:
<?php
class PDOConnection {
/**
* singleton instance
*
* @var PDOConnection
*/
protected static $_instance = null;
/**
* Returns singleton instance of PDOConnection
*
* @return PDOConnection
*/
public static function instance() {
if ( !isset( self::$_instance ) ) {
self::$_instance = new PDOConnection();
}
return self::$_instance;
}
/**
* Hide constructor, protected so only subclasses and self can use
*/
protected function __construct() {}
function __destruct(){}
/**
* Return a PDO connection using the dsn and credentials provided
*
* @param string $dsn The DSN to the database
* @param string $username Database username
* @param string $password Database password
* @return PDO connection to the database
* @throws PDOException
* @throws Exception
*/
public static function getConnection() {
$dsn = 'mysql:dbname=_____;host=_____';
$username = '_____';
$password = '_____';
$conn = null;
try {
$conn = new \PDO($dsn, $username, $password);
//Set common attributes
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $conn;
} catch (PDOException $e) {
//TODO: flag to disable errors?
}
catch(Exception $e) {
//TODO: flag to disable errors?
}
}
/** PHP seems to need these stubbed to ensure true singleton **/
public function __clone()
{
return false;
}
public function __wakeup()
{
return false;
}
}
?>
在这种情况下,我当然不推荐使用单例模式,实际上,在一般情况下也不推荐,因为在许多情况下,单例模式很难进行测试和扩展,并且不能用于一次处理多个连接,这在某些情况下可能需要 singleton模式只会使你的应用程序之间的连接更容易“全球化”,而且肯定会出名,因为当时有很多编写糟糕的php应用程序,每个脚本都会以一个新的连接开始,从而打开许多重复的连接。 但事实上,在需要的地方,直接在对象上使用global比使用singleton更好。当然,最好实现某种依赖注入或注册表模式来实现这一点,但我认为单例模式总体上是多么糟糕,尤其是在处理db时更是如此 您甚至不需要实现自己的db处理程序,甚至不需要使用任何供应商的db处理程序,就像在中所做的那样,您可以从PDO获得所需的一切:
$db = new PDO('mysql:host=localhost;dbname=myDb', 'user', 'pass');
您可以将其包装到函数/方法中,以便在返回连接之前对其进行操作,甚至可以实现最低限度的连接存储:
function getConnection($which= 'default') {
static $connections = [
// connectionName => connectionOptions
'default' => [
'dsn' => 'mysql:host=localhost;dbname=myDb',
'user' => 'user',
'pass' => 'pass',
// 'option' => value,
// ...
],
// ...
], $dbStore = [];
if (isset($dbStore[$which])) {
return $dbStore[$which];
}
if (!isset($connections[$which])) {
throw new \Exception("DB setup not supported");
}
$dbStore[$which] = new \PDO($connections[$which]['dsn'], $connections[$which]['user'], $connections[$which]['pass']);
// eventually set some options that could be stored in $connections[$which]
// $dbStore[$which]->setAttribute( ...
return $dbStore[$which];
}
这将提供与singleton相同的易用性和防止重复连接的保证,但仍然允许您一次使用多个连接:
// get default connection
$defaultDb = getConnection();
// get another connection
$anotherDb = getConnection('another');
当然,您最好将连接选项存储在某种配置中(例如,在第一次调用getConnection时获取连接)。这个例子仍然不是理想的可测试的(只是它的简单性使得它很容易模拟),但它几乎可以满足许多情况下的要求。在这种情况下,我当然不推荐单例模式,实际上,在一般情况下,因为它在许多情况下很难进行测试和扩展,并且不能用于同时处理多个连接,这在某些情况下可能需要 singleton模式只会使你的应用程序之间的连接更容易“全球化”,而且肯定会出名,因为当时有很多编写糟糕的php应用程序,每个脚本都会以一个新的连接开始,从而打开许多重复的连接。 但事实上,在需要的地方,直接在对象上使用global比使用singleton更好。当然,最好实现某种依赖注入或注册表模式来实现这一点,但我认为单例模式总体上是多么糟糕,尤其是在处理db时更是如此 您甚至不需要实现自己的db处理程序,甚至不需要使用任何供应商的db处理程序,就像在中所做的那样,您可以从PDO获得所需的一切:
$db = new PDO('mysql:host=localhost;dbname=myDb', 'user', 'pass');
您可以将其包装到函数/方法中,以便在返回连接之前对其进行操作,甚至可以实现最低限度的连接存储:
function getConnection($which= 'default') {
static $connections = [
// connectionName => connectionOptions
'default' => [
'dsn' => 'mysql:host=localhost;dbname=myDb',
'user' => 'user',
'pass' => 'pass',
// 'option' => value,
// ...
],
// ...
], $dbStore = [];
if (isset($dbStore[$which])) {
return $dbStore[$which];
}
if (!isset($connections[$which])) {
throw new \Exception("DB setup not supported");
}
$dbStore[$which] = new \PDO($connections[$which]['dsn'], $connections[$which]['user'], $connections[$which]['pass']);
// eventually set some options that could be stored in $connections[$which]
// $dbStore[$which]->setAttribute( ...
return $dbStore[$which];
}
这将提供与singleton相同的易用性和防止重复连接的保证,但仍然允许您一次使用多个连接:
// get default connection
$defaultDb = getConnection();
// get another connection
$anotherDb = getConnection('another');
当然,您最好将连接选项存储在某种配置中(例如,在第一次调用getConnection时获取连接)。而且这个示例仍然不是理想的可测试性(只是它的简单性使其易于模拟),但它几乎可以满足许多情况下的要求。我建议不要使用“mysql”php库。它已被弃用。请改用PDO驱动程序。@davidvellla这就是为什么我尝试使用mysqli_connect,因为旧的mysql_connect已被弃用。我把这一点放在我的问题中澄清。此外,PDO连接函数也不能与define()函数配合使用。有很多更好的方法可以做到这一点。我建议不要使用“mysql”php库,而不要使用定义。它已被弃用。请改用PDO驱动程序。@davidvellla这就是为什么我尝试使用mysqli_connect,因为旧的mysql_connect已被弃用。我把这一点放在我的问题中澄清。此外,PDO连接函数也不能与define()函数一起使用还有更好的方法