我一直在尝试制作 OOP PHP5 代码。但我认为我的尝试很笨拙。这些是我的问题:
- 他们是包含数据库配置信息的更好、更精简的方法吗?
- 我能以某种方式绕过必须在我制作的每个函数中声明 $db = new Db() 吗?
- 我应该使用 PEAR 作为数据库抽象层而不是 Mysqli_database.php 吗?
mysqli_database.php
<?php
class Db {
private $connection;
private function open_connection() {
if (file_exists('config.inc.php')) {
require('config.inc.php');
} else {
require('../config.inc.php');
}
try
{
$this->connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
}
catch (Exception $e)
{
throw $e;
}
}
private function close_connection() {
try
{
mysqli_close($this->connection);
}
catch (Exception $e)
{
throw $e;
}
}
public function query($query) {
try
{
$this->open_connection();
$result = mysqli_query($this->connection,$query);
return $result;
}
catch (Exception $e)
{
throw $e;
}
$this->close_connection();
}
public function fetchArray($query) {
$row = mysqli_fetch_assoc($query);
return $row;
}
public function count_rows($query) {
$row = mysqli_num_rows($query);
return $row;
}
public function rows_affected() {
$row = mysqli_affected_rows($this->connection);
return $row;
}
public function created_id() {
$row = mysqli_insert_id($this->connection);
return $row;
}
}
?>
测试数据.php
<?php
class Test_data {
public function show_text() {
$db = new Db();
$sql = $db->query("SELECT * FROM test_table");
$row = $db->fetchArray($sql);
echo 'This is the output: '.$row['text'];
}
}
?>
配置文件
<?php
$dbname = 'database_name';
$dbhost = 'localhost';
$dbuser = 'database_user';
$dbpass = 'database_password';
?>
包括.php
<?php
require_once('config.inc.php');
require_once('Mysqli_database.php');
$db = new Db();
$test_data = new Test_data();
?>
索引.php
<?php
require_once('includes.php');
$test_data->show_text();
?>