PHP-OOP-MySQL连接
在以前的项目中,我使用以下代码连接到MySQL数据库: 文件:connect.phpPHP-OOP-MySQL连接,php,mysql,oop,Php,Mysql,Oop,在以前的项目中,我使用以下代码连接到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_USE
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
两种解决方案都有效,但
问题是:
- 这是必要的还是我过度复杂了这些脚本
- 在这方面是否有最佳做法
<?php
//Enter your database connection details here.
$host = 'localhost'; //HOST NAME.
$db_name = 'databasename'; //Database Name
$db_username = 'root'; //Database Username
$db_password = ''; //Database Password
try
{
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
}
catch (PDOException $e)
{
exit('Error Connecting To DataBase');
}
?>
database.class.php:
<?php
class database
{
function __construct($pdo)
{
$this->pdo = $pdo;
}
function getData()
{
$query = $this->pdo->prepare('SELECT * FROM database');
$query->execute();
return $query->fetchAll();
}
}
?>
index.php:
<?php
require_once 'config.php';
require_once 'database.class.php';
$db = new database($pdo);
$rows = $db->getData();
?>
可能会有不同的意见..但代码看起来很好$connection=mysqli\u connect($db\u server,$db\u username,$db\u password,$db\u database)代码>你工作太辛苦了。我注意到三件事:你只需要使用一次require_。。。您也使用对象(我的旧方法和新方法的组合),并且您使用PDO作为包装器,对吗?这种方法的优点是什么?