oop连接mysql数据库_php – OOP数据库连接/断开类

我刚刚开始学习面向对象编程的概念,并将一个用于连接数据库,选择数据库和关闭数据库连接的类组合在一起.到目前为止,除了关闭与数据库的连接外,一切似乎都没问题.

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
';

}

public function select($database){

mysql_select_db($database)

OR die("There was a problem selecting the database.");

echo 'successfully selected database
';

}

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();

当我尝试断开与数据库的连接时,我收到以下错误消息:

Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in F:\Programs\webserver\root\oop\oop.php on line 53

我猜这不像在mysql_close函数的括号中放置connectdb方法那么简单,但找不到正确的方法.

谢谢

解决方法:

我会在你的类中添加一个连接/链接变量,并使用析构函数.

这也将使您不必忘记关闭连接,因为它会自动完成.

您需要传递给mysql_close()的是$this->链接.

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.");

}

}

用法示例:

$db = new Database("localhost", "username", "password", "testDatabase");

$result = $db->query("SELECT * FROM students");

while ($row = mysql_fetch_assoc($result)) {

echo "First Name: " . $row['firstname'] ."
";

echo "Last Name: " . $row['lastname'] ."
";

echo "Address: " . $row['address'] ."
";

echo "Age: " . $row['age'] ."
";

echo "


";

}

?>

编辑:

所以人们实际上可以使用这个类,我添加了缺少的属性/方法.

下一步是扩展查询方法,包括注入保护和任何其他帮助函数.

我做了以下更改:

>添加了缺少的私有属性

>添加了__construct($host,$username,$password,$database)

>将connectdb()和select()合并到__construct()中,以节省额外的两行代码.

>添加了查询($query)

>示例用法

如果我写了一个错字或错误,请留下建设性的评论,以便我可以为其他人解决.

编辑23/06/2018

正如所指出的那样,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.");

}

}

用法示例:

$db = new Database("localhost", "username", "password", "testDatabase");

$result = $db->query("SELECT * FROM students");

if(true == $result['success'])

{

echo "Number of rows: " . $result['count'] ."
";

foreach($result['rows'] as $row)

{

echo "First Name: " . $row['firstname'] ."
";

echo "Last Name: " . $row['lastname'] ."
";

echo "Address: " . $row['address'] ."
";

echo "Age: " . $row['age'] ."
";

echo "


";

}

}

if(false == $result['success'])

{

echo "An error has occurred: " . $result['error'] ."
";

}

?>

来源:https://www.icode9.com/content-2-323701.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值