0

Here is mycode dbclass.php i am new for oops concept,

<?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'];
   }
?>

if i run this code it showing database not connected. I don't know why?

4

1 回答 1

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);
于 2013-10-10T08:57:25.817 回答