我刚刚开始学习面向对象编程的概念,并且已经组合了一个用于连接数据库,选择数据库和关闭数据库连接的类。到目前为止,除了关闭与数据库的连接外,一切似乎都没问题。
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();
当我尝试断开与数据库的连接时,收到以下错误消息:
Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in F:\Programs\webserver\root\oop\oop.php on line 53
我猜测它并不像将connectdb方法放在mysql_close函数的括号中那么简单,但无法找到正确的方法。
由于
答案 0 :(得分:13)
我会在你的类中添加一个连接/链接变量,并使用析构函数。 这也将使您不必记住关闭连接,因为它会自动完成 您需要将$ this-&gt;链接传递给mysql_close()。
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.");
}
}
示例用法:
<?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 />";
}
?>
编辑:
所以人们实际上可以使用这个类,我添加了缺少的属性/方法
下一步是扩展查询方法,包括注入保护和任何其他帮助函数
我做了以下更改:
__construct($host, $username, $password, $database)
connectdb()
和select()
合并到__construct()
中,可以节省额外的两行代码。query($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.");
}
}
使用示例:
<?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 />";
}
?>
答案 1 :(得分:2)
你没有从connectdb()
返回任何内容,但是你已经将此函数返回mysql_close()
。
答案 2 :(得分:2)
你应该知道在PHP 4中引入了mysql_*
函数,这些函数已经超过了你的1。这个API非常陈旧,而且这个过程实际上已经开始deprecating this extension。
您不应该在2012年使用mysql_*
函数编写新代码。
有两个非常好的选择:PDO和MySQLi。两者都已经考虑了面向对象的代码,并且它们还使您能够使用prepared statements。
您在用PDO编写的原始帖子中显示的示例如下所示:
//connect to the the database
$connection = new PDO('mysql:host=localhost;dbname=msm', 'username', 'password');
//disconnects
$connection = null;
当然,还有更复杂的用例,但需要进一步发展。
答案 3 :(得分:1)
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();
答案 4 :(得分:0)
面向对象编程与PDO和mysqli配合得很好。试一试
答案 5 :(得分:-2)
<?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;
?>