gpt4 book ai didi

PHP OOP MySQL 连接

转载 作者:可可西里 更新时间:2023-11-01 09:05:37 25 4
gpt4 key购买 nike

<分区>

在之前的项目中,我使用如下代码连接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.

现在,我尝试在我的编程中使用更多 OOP 方法,然后我创建下一个代码以连接到 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

两种解决方案都有效,但是......

问题是:

  • 这是必要的还是我让这些脚本过于复杂了?
  • 在这方面是否有最佳实践?

提前感谢您提出任何意见以改进这一切。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com