在之前的项目中,我使用以下代码连接到MySQL数据库:
文件:connect.php
define('DB_SERVER','my_server');
define('DB_DATABASE','my_database');
define('DB_SERVER_USERNAME','my_user');
define('DB_SERVER_PASSWORD','my_password');
$db_server = DB_SERVER;
$db_username = DB_SERVER_USERNAME;
$db_password = DB_SERVER_PASSWORD;
$db_database = DB_DATABASE;
$connection = mysqli_connect($db_server, $db_username, $db_password,$db_database);
if ($connection) {
//Connected OK
} else {
die ("Cannot connect to database $db_database in $db_server!");
}
我的其他脚本都长得像这样:
include "connect.php"
//From here, I can use the $connection variable to select/insert/delete/update data in my_database.
现在,我正在尝试在我的编程中使用更多的面向对象方法,然后我创建了以下代码来连接MySQL:
Class Connection extends mysqli{
public function __construct(){
if ($config = parse_ini_file('config/config.ini',true)){
$server = $config['database']['server'];
$username = $config['database']['username'];
$password = $config['database']['password'];
$database = $config['database']['dbname'];
parent::__construct($server,$username,$password,$database);
if (mysqli_connect_error()){
$message = "Conection error (" . mysqli_connect_errno() . ") " .
mysqli_connect_error();
throw new Exception($message);
}
} else {
$message = "Config file not found.";
throw new Exception($message);
}
}
}
我的脚本现在看起来像这样:
set_include_path(__DIR__.'/Classes');
spl_autoload_extensions(".php");
spl_autoload_register();
try {
$connection = new Connection();
} catch (Exception $ex){
die($ex->getMessage());
}
//Again, from here I can use the variable $connection to use my database
两种解决方案都可以,但是...
问题是:
- 这是否必要或者我让脚本过于复杂了?
- 在这方面有最佳实践吗?
提前感谢任何改进所有内容的评论。
$connection = mysqli_connect($db_server, $db_username, $db_password, $db_database);
你工作太辛苦了,只需使用常量即可。 - Funk Forty Niner