[英]OOP database connect/disconnect class
我剛剛開始學習面向對象編程的概念,並將一個用於連接數據庫,選擇數據庫和關閉數據庫連接的類組合在一起。 到目前為止,除了關閉與數據庫的連接外,一切似乎都沒問題。
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
我猜這不像在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.");
}
}
用法示例:
<?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 />";
}
?>
你沒有從connectdb()
返回任何東西但是你正在傳遞這個函數返回mysql_close()
。
你應該知道在PHP 4中引入了mysql_*
函數,這些函數已經超過了你的1。 此API非常陳舊,並且該過程已開始實際棄用此擴展 。
您不應該在2012年使用mysql_*
函數編寫新代碼。
有兩個非常好的選擇: PDO和MySQLi 。 兩者都已經考慮了面向對象的代碼,並且它們還使您能夠使用預准備語句 。
您在使用PDO編寫的原始帖子中顯示的示例如下所示:
//connect to the the database
$connection = new PDO('mysql:host=localhost;dbname=msm', 'username', 'password');
//disconnects
$connection = null;
當然,有更復雜的用例,但有時間要進化。
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();
面向對象編程與PDO和mysqli配合得很好。 試試看
<?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;
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.