php OOP 数据库连接/断开类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9651038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
OOP database connect/disconnect class
提问by crmepham
I have just started learning the concept of Object oriented programming and have put together a class for connecting to a database, selecting database and closing the database connection. So far everything seems to work out okay except closing the connection to the database.
我刚刚开始学习面向对象编程的概念,并整理了一个用于连接数据库、选择数据库和关闭数据库连接的类。到目前为止,除了关闭与数据库的连接之外,一切似乎都正常。
class Database {
private $host, $username, $password;
public function __construct($ihost, $iusername, $ipassword){
$this->host = $ihost;
$this->username = $iusername;
$this->password = $ipassword;
}
public function connectdb(){
mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
echo 'successfully connected to database<br />';
}
public function select($database){
mysql_select_db($database)
OR die("There was a problem selecting the database.");
echo 'successfully selected database<br />';
}
public function disconnectdb(){
mysql_close($this->connectdb())
OR die("There was a problem disconnecting from the database.");
}
}
$database = new database('localhost', 'root', 'usbw');
$database->connectdb();
$database->select('msm');
$database->disconnectdb();
When I attempt to disconnect from the database I get the following error message:
当我尝试与数据库断开连接时,我收到以下错误消息:
Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in F:\Programs\webserver\root\oop\oop.php on line 53
I'm guessing it isn't as simple as placing the connectdb method within the parenthesis of the mysql_close function but can't find the right way to do it.
我猜它不像将 connectdb 方法放在 mysql_close 函数的括号内那么简单,但找不到正确的方法来做到这一点。
Thanks
谢谢
回答by Bradmage
I would add a connection/link variable to your class, and use a destructor.
That will also save you from haveing to remember to close your connection, cause it's done automatically.
It is the $this->link that you need to pass to your mysql_close().
我会在你的类中添加一个连接/链接变量,并使用析构函数。这也将使您不必记住关闭连接,因为它是自动完成的。
这是您需要传递给 mysql_close() 的 $this->link。
class Database {
private $link;
private $host, $username, $password, $database;
public function __construct($host, $username, $password, $database){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->link = mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
mysql_select_db($this->database, $this->link)
OR die("There was a problem selecting the database.");
return true;
}
public function query($query) {
$result = mysql_query($query);
if (!$result) die('Invalid query: ' . mysql_error());
return $result;
}
public function __destruct() {
mysql_close($this->link)
OR die("There was a problem disconnecting from the database.");
}
}
Example Usage:
示例用法:
<?php
$db = new Database("localhost", "username", "password", "testDatabase");
$result = $db->query("SELECT * FROM students");
while ($row = mysql_fetch_assoc($result)) {
echo "First Name: " . $row['firstname'] ."<br />";
echo "Last Name: " . $row['lastname'] ."<br />";
echo "Address: " . $row['address'] ."<br />";
echo "Age: " . $row['age'] ."<br />";
echo "<hr />";
}
?>
Edit:
So people can actually use the class, I added the missing properties/methods.
The next step would be to expand on the query method, to include protection against injection, and any other helper functions.
I made the following changes:
编辑:
所以人们可以实际使用该类,我添加了缺少的属性/方法。
下一步是扩展查询方法,包括防止注入和任何其他辅助函数。
我做了以下更改:
- Added the missing private properties
- Added
__construct($host, $username, $password, $database)
- Merged
connectdb()
andselect()
into__construct()
saving an extra two lines of code. - Added
query($query)
- Example Usage
- 添加了缺少的私有属性
- 添加
__construct($host, $username, $password, $database)
- 合并
connectdb()
和select()
成__construct()
节省一个额外的代码两行。 - 添加
query($query)
- 示例用法
Please if I made a typo or mistake, leave a constructive comment, so I can fix it for others.
如果我打错字或错误,请留下建设性的评论,以便我可以为其他人修复。
edit 23/06/2018
编辑 23/06/2018
As pointed out mysql is quite outdated and as this question still receives regular visits I thought I'd post an updated solution.
正如所指出的 mysql 已经过时了,并且由于这个问题仍然定期访问,我想我会发布更新的解决方案。
class Database {
private $mysqli;
private $host, $username, $password, $database;
/**
* Creates the mysql connection.
* Kills the script on connection or database errors.
*
* @param string $host
* @param string $username
* @param string $password
* @param string $database
* @return boolean
*/
public function __construct($host, $username, $password, $database){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->mysqli = new mysqli($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$this->mysqli->select_db($this->database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return true;
}
/**
* Prints the currently selected database.
*/
public function print_database_name()
{
/* return name of current default database */
if ($result = $this->mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Selected database is %s.\n", $row[0]);
$result->close();
}
}
/**
* On error returns an array with the error code.
* On success returns an array with multiple mysql data.
*
* @param string $query
* @return array
*/
public function query($query) {
/* array returned, includes a success boolean */
$return = array();
if(!$result = $this->mysqli->query($query))
{
$return['success'] = false;
$return['error'] = $this->mysqli->error;
return $return;
}
$return['success'] = true;
$return['affected_rows'] = $this->mysqli->affected_rows;
$return['insert_id'] = $this->mysqli->insert_id;
if(0 == $this->mysqli->insert_id)
{
$return['count'] = $result->num_rows;
$return['rows'] = array();
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$return['rows'][] = $row;
}
/* free result set */
$result->close();
}
return $return;
}
/**
* Automatically closes the mysql connection
* at the end of the program.
*/
public function __destruct() {
$this->mysqli->close()
OR die("There was a problem disconnecting from the database.");
}
}
Example usage:
用法示例:
<?php
$db = new Database("localhost", "username", "password", "testDatabase");
$result = $db->query("SELECT * FROM students");
if(true == $result['success'])
{
echo "Number of rows: " . $result['count'] ."<br />";
foreach($result['rows'] as $row)
{
echo "First Name: " . $row['firstname'] ."<br />";
echo "Last Name: " . $row['lastname'] ."<br />";
echo "Address: " . $row['address'] ."<br />";
echo "Age: " . $row['age'] ."<br />";
echo "<hr />";
}
}
if(false == $result['success'])
{
echo "An error has occurred: " . $result['error'] ."<br />";
}
?>
回答by Not_a_Golfer
you're not returning anything from connectdb()
yet you're passing this function's return to mysql_close()
.
您没有从中返回任何内容,connectdb()
但您正在将此函数的返回值传递给mysql_close()
.
回答by tere?ko
You should be aware that mysql_*
functions were introduced in PHP 4, which is more then 1 yours ago. This API is extremely old, and the process has begun to actually deprecating this extension.
您应该知道mysql_*
函数是在 PHP 4 中引入的,它比您之前的 1 多。这个 API 非常古老,而且这个过程已经开始实际弃用这个扩展。
You should not in 2012 write new code with mysql_*
functions.
你不应该在 2012 年编写带有mysql_*
函数的新代码。
There exist two very good alternative : PDOand MySQLi. Both of which are already written with object oriented code in mind, and they also give you ability to use prepared statements.
有两个很好的选择:PDO和MySQLi。两者都已经考虑到面向对象的代码编写,并且它们还使您能够使用准备好的语句。
That example you showed in the original post written with PDO would look like this:
您在用 PDO 编写的原始帖子中显示的示例如下所示:
//connect to the the database
$connection = new PDO('mysql:host=localhost;dbname=msm', 'username', 'password');
//disconnects
$connection = null;
Of course there are more complicated use-case, but the point stand - time to evolve.
当然还有更复杂的用例,但关键是要发展。
回答by tere?ko
mysql_close requires a parameter to disconnect but you are providing nothing.
mysql_close 需要一个参数来断开连接,但您什么也没提供。
class Database { private $host, $username, $password, $con; public function __construct($ihost, $iusername, $ipassword){ $this->host = $ihost; $this->username = $iusername; $this->password = $ipassword; $this->con = false; } public function connect() { $connect = mysql_connect($this->host, $this->username, $this->password); return $connect; } public function connectdb(){ $conn = $this->connect(); if($conn) { $this->con = true; echo "Successsfully Connected.
"; return true; } else { echo "Sorry Could Not Connect.
"; return false; } } public function select($database){ if($this->con) { if(mysql_select_db($database)) { echo "Successfully Connected Database. $database.
"; return true; } else { echo "Unknown database.
"; } } else { echo "No active Connection.
"; return false; } } public function disconnectdb(){ if($this->con) { if(mysql_close($this->connect())) { $this->con = false; echo "Successfully disconnected.
"; return true; } } else { echo "Could Not disconnect.
"; return false; } } } $database = new database('localhost', 'root', ''); $database->connectdb(); $database->select('databaseoffacebook'); $database->disconnectdb();
回答by blakroku
Object Oriented Programming works well with PDO and mysqli. Give it a try
面向对象编程适用于 PDO 和 mysqli。试一试
回答by Lalit Dogra
<?php
class Database{
private $link;
//private $host,$username,$password,$database;
//private $status;
public function __construct(){
$this->host = 'localhost';
$this->username = 'root';
$this->password = '';
$this->database = 'workclass';
$this->link = mysqli_connect($this->host,$this->username,$this->password);
$this->status = mysqli_select_db($this->link,$this->database);
if (!$this->status) {
return $this->status="Failed to Connected with Database";
}else{
return $this->status="Database is connected";
}
}
}
$object = new Database();
echo $object->status;
?>