在 PHP 中设置数据库连接类
Posted
技术标签:
【中文标题】在 PHP 中设置数据库连接类【英文标题】:Setting up a database connection class in PHP 【发布时间】:2016-04-30 13:20:34 【问题描述】:我最近被介绍到 php 中的类的概念,经过一些研究,我得出的结论是,我需要将数据库相关的函数存储在一个类中以供以后访问。它在大多数情况下都有效,但我仍然对一些用例感到困惑。例如,
以下是我通常如何连接到我的数据库并在表格中显示来自用户 ID 的信息的示例
dbcon.php:
<?php
$con = mysqli_connect("host","username","password","database") or die("Couldn't connect");
require_once("functions.php");
?>
functions.php
function getUserInfo($id)
$query = mysqli_query($con, "SELECT * FROM users WHERE id = '$id'");
return mysqli_fetch_array($query);
一些随机文件:
require_once("dbcon.php");
$result = mysqli_query($con, "SELECT * FROM tablename");
while ($row = mysqli_fetch_assoc($result))
$userinfo = getUserInfo($row['userid']);
echo $userinfo['name'];
?>
我不认为这种查询数据库和显示信息的方法是最简洁或最有效的方法。我阅读了this 文章,关于使用类来篡改数据库并调用我在类中创建的函数。
我的第一个问题是:当我尝试访问functions.php 中的$con 时,它是未定义的。如何通过 require_once 函数将变量从 dbcon.php 传递给 functions.php?
我还想知道存储与数据库的连接的最佳方法是什么,以及是否有任何关于如何设置它的教程。
希望你能理解,哈哈。
【问题讨论】:
php.net/manual/en/class.mysqli.php 实际上已经有一个类 :) @developernaren 好当。你每天都会学到新东西:D 如果您创建一个类来管理您的连接,并且您使用 require_once 命令添加该类文件。你只需要实例化类$myDBclass = new DBClass()
,然后使用你类中的con变量,比如$myDBClass->con
【参考方案1】:
你可以这样做:-
Dbconnection.php:-
<?php
Class DbConnection
function getdbconnect()
$conn = mysqli_connect("host","username","password","database") or die("Couldn't connect");
return $conn;
?>
Function.php:-
<?php
require_once('Dbconnection.php');
Class WorkingExamples
function getUserInfo($id)
$Dbobj = new DbConnection();
$query = mysqli_query($Dbobj->getdbconnect(), "SELECT * FROM users WHERE id = '$id'");
return mysqli_fetch_array($query);
$data = new WorkingExamples();
echo "<pre/>";print_r($data->getUserInfo(3));
?>
注意:- 这是一个示例,请根据您的要求更改值并获得结果。
【讨论】:
【参考方案2】:<?php
class DatabaseConnection
private $host = "127.0.0.1";
private $dbname = "online_english";
private $dbUsername = "root";
private $dbPass = "";
private $charset = 'utf8mb4';
private $dsn;
public function tryConnect()
try
$this->dsn = "mysql:host=$this->host;dbname=$this->dbname;charset=$this->charset";
$DBH = new PDO($this->dsn,$this->dbUsername,$this->dbPass);
$DBH->exec("set names utf8");
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $DBH;
catch (PDOException $e)
$e->getMessage();
?>
【讨论】:
【参考方案3】: <?php
class Database
const DB_HOSTNAME = 'localhost';
const DB_USERNAME = 'root';
const DB_PASSWORD = 'root';
const DB_NAME = 'stockganesha';
public $_db_connect;
protected $_sql;
protected $_result;
protected $_row;
function db_connect()
$this->_db_connect = mysqli_connect(self::DB_HOSTNAME,self::DB_USERNAME,self::DB_PASSWORD,self::DB_NAME) or die(mysql_error());
return $this->_db_connect;
function sql()
$this->_sql = 'SELECT * FROM customers';
function query()
$this->_result = mysqli_query($this->_db_connect,$this->_sql);
function fetch_array()
while($this->_row = mysqli_fetch_array($this->_result))
$username = $this->_row['first_name'];
echo "<ul>";
echo "<li>".$username."</li>";
echo "</ul>";
function db_close()
mysqli_close($this->_db_connect);
并将其导入另一个类
<?php
require_once('../Config/Dbconnection.php');
include './model.php';
class CustomerDTO
private $mysql;
function __construct()
$database = new Database();
$this->mysql = $database->db_connect();
function create($customer)
$firstName = $customer->getFirstName();
$lastName = $customer->getLastName();
$emailId = $customer->getEmailId();
$mobileNumber = $customer->getMobileNumber();
$dateOfBirth = $customer->getDateOfBirth();
$phoneNumber = $customer->getPhoneNumber();
$termAndCondtion = $customer->getTermAndCondition();
$result = mysqli_query($this->mysql, "Insert into customers (first_name,last_name,email_id,mobile_number,date_of_birth,phone_number,term_and_condition)
values('$firstName','$lastName','$emailId','$mobileNumber','$dateOfBirth','$phoneNumber','$termAndCondtion')");
return $result;
function read()
$result = mysqli_query( $this->mysql, "Select * from customers");
return $result;
function update($id, $customer)
$result = mysqli_query($this->mysql, "update customers set
first_name = ".$customer->getFirstName()."
last_name = ".$customer->getLastName()."
email_id = ".$customer->getEmailId()."
mobile_number = ".$customer->getMobileNumber()."
date_of_birth = ".$customer->getDateOfBirth()."
phone_number = ".$customer->getPhoneNumber()."
term_and_condition = ".$customer->getTermAndCondition()."
where id = ".$customer->getId());
return $result;
public function delete($id)
$result = mysqli_query($this->mysql, "delete from customers where id =".$id);
return $result;
【讨论】:
将数据库连接用户名和密码设置为常量是真的不好的做法。这使得 PHP 应用程序全局可用,这是一个重要的安全问题。 您的连接值仅使用一次,并且仅在脚本后面的几行中使用,因此只需将它们设为私有变量。连接成功后unset
他们。
这只是一个例子@Martin,但感谢您的建议。很高兴听到你的声音。以上是关于在 PHP 中设置数据库连接类的主要内容,如果未能解决你的问题,请参考以下文章