使用php类和方法的数据库连接

时间:2013-10-10 08:54:22

标签: php mysql oop

这是mycode dbclass.php我是oops概念的新手,

<?php
   class Database {
      private $link;
      private $hostname, $username, $password, $dbname;
      public function __construct( $hostname, $username, $password, $dbname ) {
         $this->link=mysql_connect($this->hostname,$this->username,$this->password) or die("Mysql Connection error!!");
         mysql_select_db($this->dbname,$this->link) or die("error:".mysql_error());
         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("Error:".mysql_error());
      }
   }    
?>
<?php 
   include("dbclass.php");
   $db = new Database("localhost", "root", "password", "test");
   $result = $db->query("select * from messages");
   while ( $row = mysql_fetch_array( $result ) ) {
      echo $row['id'];
   }
?>

如果我运行此代码,则显示数据库未连接。我不知道为什么?

1 个答案:

答案 0 :(得分:2)

问题在于:

$this->link=mysql_connect($this->hostname,$this->username,$this->password)

您没有将函数中的参数赋值给类的变量。因此这样做

$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;

然后给:

 $this->link=mysql_connect($this->hostname,$this->username,$this->password);