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

标签 php mysql oop

这是我的代码 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'];
   }
?>

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

最佳答案

问题就在这里:

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

关于php - 使用 php 类和方法连接数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19291266/

相关文章:

mysql - 带有 Typescript 的 NodeJS MySQL 中的数据库 Controller

mysql - Flutter SQFLite Assets 数据库

c++ - 管理指向派生对象的指针集合的最佳方法

c++ - 访问者模式是区分 C++ 中参数类型的最快方法吗?

python - QTabWidget 不允许我使用自定义类

php - API -> JSON -> MySQL

php - 用 Symfony2 翻译 YML 格式的占位符,可以吗?

php - 发送 UTF8 header 时页面上的黑色菱形问号字符

php - 是否有适用于PHP或Ruby的网络搜寻器库?

MySQL 列的字符集转换是否会影响现有值