【问题标题】:Database connection through class通过类连接数据库
【发布时间】:2013-04-29 08:28:49
【问题描述】:

我想创建一个包含各种通用变量和函数的类,以便在整个网站中使用。其中之一将是数据库连接。我正在尝试以下代码:

class Sys {
  public $dbc = new mysqli('localhost', 'user', 'pass', 'db');
  $dbc->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
}

$system = new Sys;

它在课堂的第一行给了我一个语法错误......我做错了什么? 谢谢

【问题讨论】:

    标签: php database class connect


    【解决方案1】:

    你应该在构造函数中做这样的事情。您只能在初始声明中设置原语。创建对象时还需要大括号。

    class Sys {
      private $dbc;
      private $someInteger = 4; // you can do this
      private $someArray = array(); // and this.
    
      public function __construct()
      {
        $this->dbc = new mysqli('localhost', 'user', 'pass', 'db');
        $this->dbc->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
      }
    
      public function getDbc()
      {
        return $this->dbc;
      }
    
    }
    
    $system = new Sys();
    //$system->getDbc()->soSomethingWithMyDb(); 
    

    我建议你阅读使用对象:http://php.net/manual/en/language.types.object.php

    【讨论】:

      【解决方案2】:

      您应该只声​​明一个公共 $dbc。

      然后有一个构造函数function __construct() { ...... } 在那里你初始化它/设置它。

      class Sys {
          public $dbc;
      
          function __construct() {
              $this->dbc = new mysqli('localhost', 'user', 'pass', 'db');
              $this->dbc->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
          }
      }
      
      $system = new Sys;
      

      【讨论】:

      • 我宁愿将 $dbc 设为私有并使用 getDbc() 方法。不要打扰我的连接! :-)
      • 非常正确:我也会更新我的答案。快速复制他的代码。
      • 这似乎超出了问题的范围。 :)
      【解决方案3】:
      class Sys {
        var $mysqli;
        function DB($database,$server,$user,$pass) {
          $this->mysqli = mysqli_connect($server, $user, $pass, $base) or die('Server connection not possible. '. mysqli_connect_error());
        }
      }
      
      include("db.class.mysqli.php"); // db handler class
      // Open the base (construct the object):
      $db = new Sys(DB_NAME, SERVER_NAME, USER_NAME, PASSWORD);
      

      我就是这样做的

      【讨论】:

      • 除非我假设您的课程称为 DB。并使用 php4 构造函数语法。很可能忘记更改构造函数名称。函数也应该称为“Sys”甚至更好(如果使用 php5)__construct
      • 正确,因为我只是复制和粘贴而没有注意:) 是的,使用 php4 作为它的遗留类,我从未有机会更新以使用 __construct 仍然有效,因此没有大量理由更新它:)
      【解决方案4】:

      查看 php 中魔术方法 http://php.net/manual/en/language.oop5.magic.php 的使用 - 如上所述,您的类需要 __construct 方法才能工作。下面是 Peter Lavin 的书 Object Oriented PHP http://objectorientedphp.com/ 第 9 章中的示例。

      class MySQLConnect {
      
      // Data Members
      private $connection;
      private static $instances = 0;
      
      // Constructor
      public function __construct($hostname, $username, $password) {
          if(MySQLConnect::$instances == 0) {
              $this->connection = new mysqli($hostname, $username, $password);
              // Check for Errors then report them
              if ($this->connection->connect_error) {
                  die("Connect Error ($this->connection->connect_errno) $this->connection->connect_error");
              }
              // Set the Class variable $instances to 1
              MySQLConnect::$instances = 1;
          } else {
              $msg = "There's another instance the MySQLConnect Class with a connect open already. Close it";
              die($msg);
      
          }
      
      }
      }
      

      【讨论】:

        【解决方案5】:

        试试这个:

        $db = new DB;
        $link = $db->connect()->getLink();
        
        class DB {
        
            public $connection = array();
        
            public function __construct() {
                return $this;
            }
        
            public function connect($host=null, $user=null, $pass=null, $database=null) {
                $this->connection = new Connection($host, $user, $pass, $database);
                $this->connection->connect();
                $this->link = $this->connection->getLink();
                if ($this->connection->ping()) {
                    if (!is_null($database)) {
                        if (!$this->connection->databaseConnect($database)) {
                            throw new\Exception('Unable to connect to the server.');
                        }
                    }
                }else{
                    throw new \Exception('Unable to connect to the server.');
                }
                return $this;
            }
        
            public function getLink() {
                return $this->link;
            }
        
        }
        
        class Connection {
        
            protected $chost='localhost';
            protected $cuser='guest';
            protected $cpass='password';
            protected $cdatabase='PROFORDABLE';
        
            function __construct($host=null, $user=null, $pass=null, $database=null) {
        
                $host = !is_null($host) ? $host : $this->chost;
                $user = !is_null($user) ? $user : $this->cuser;
                $password = !is_null($pass) ? $pass : $this->cpass;
                $database = !is_null($database) ? $database : $this->cdatabase;
        
                $this->set('host', $host)->set('user', $user)->set('password', $password)->set('database', $database);
                return $this;
            }
        
            public function connect() {
                $link = mysqli_connect($this->host->getHost(), $this->user->getUser(), $this->password->getPassword());
                if (!is_object($link)) {
                    throw new \Exception("An error has occurred while connecting to the server.");
                }
                $this->link = $link;
            }
        
            public function databaseConnect($database) {
                if (!mysqli_select_db($this->getLink(), $database)) {
                    throw new \Exception("Unable to select the database.");
                }
            }
        
            public function getLink() {
                return $this->link;
            }
        
            public function ping() {
                if (mysqli_ping($this->link)) {
                    return TRUE;
                }
                return FALSE;
            }
        
            public function set($name, $param) {
                if (!isset($name) || !isset($param)) return $this;
                $class = __NAMESPACE__.'\\'.ucwords($name);
                $this->$name = new $class($param);
                return $this;
            }
        
            public function get($name) {
                $getfunc = 'get'.ucwords($name);
                return $this->$name->$getFunc();
            }
        
        }
        
        class Host {
            public function __construct($host) {
                $this->setHost($host);
            }
            public function setHost($host) {
                $this->host = $host;
            }
            public function getHost() {
                return $this->host;
            }
        }
        
        class User {
        
            public function __construct($user) {
                $this->setUser($user);
            }
        
            public function setUser($user) {
                $this->user = $user;
            }
        
            public function getUser() {
                return $this->user;
            }
        
        }
        
        class Password {
        
            public function __construct($password) {
                $this->setPassword($password);
            }
        
            public function setPassword($password) {
                $this->password = $password;
            }
        
            public function getPassword() {
                return $this->password;
            }
        
            public function sha($value) {
                return sha1($value);
        
            }
        
        }
        
        class guestPassword extends Password {
            const PASSWORD='password';
            public function __construct() {
                return PASSWORD;
            }
        }
        
        class Database {
        
            public function __construct($database) {
                $this->setDatabase($database);
            }
        
            public function setDatabase($database) {
                $this->database = $database;
            }
        
            public function getDatabase() {
                return $this->database;
            }
        
        }
        
        class Query {
        
        
        }
        

        【讨论】:

          【解决方案6】:
          //Create mysql.php and paste following code
          
             <?php
          
              class MySQL {
               private $set_host;
               private $set_username;
               private $set_password;
               private $set_database;
          
               public function __Construct($set_host, $set_username, $set_password) {
                  $this->host = $set_host;
                  $this->username = $set_username;
                  $this->password = $set_password;
               $con = mysql_connect($this->host, $this->username, $this->password);
              if (!$con) {
                die("Couldn't connect to the server");
              }
              }
              //end of __construct
              //connect to database
              public function Database($set_database) {
              $this->database = $set_database;
              mysql_query("set character_set_server='utf8'");
              mysql_query("set names 'utf8'");
              mysql_select_db($this->database) or die("Unable to select database");
              }
          
            //fetch data from any table
              public function fetch_data($sql) {
              $this->sql = $sql;
              $query = mysql_query($this->sql);
              $result = array();
              while ($record = mysql_fetch_array($query)) {
                $result[] = $record;
              }
              return $result;
              }
          
               //fetch all columns from any table to be used for INSERT INTO.
               public function get_all_columns($table_name) {
              $this->table_name = $table_name;
              $sql = "SHOW COLUMNS FROM $this->table_name";
              $result = mysql_query($sql);
              while ($record = mysql_fetch_array($result)) {
                $fields[] = $record['0'];
              }
              $val = '';
              foreach ($fields as $value) {
                $val .= $value . ',';
              }
              $vals = rtrim($val, ',');
                 return $vals;
                }
          
              //insert data to any table by $_POST or set of variables separated by ,
              public function insert_data($tbl_name, $tbl_value) {
              $this->tbl_name = $tbl_name;    
              $this->tbl_value = $tbl_value;
          //use mysql_real_escape_string($tbl_value) to clean & insert data.
              $this->tbl_col = $this->get_all_columns($this->tbl_name);
              $sql = "INSERT INTO $this->tbl_name ($this->tbl_col) VALUES ($this->tbl_value)";
              $query_result = mysql_query($sql);
            }    
          //end of insert data
          
              public function delete_data($del_id, $table_name) {
              $this->del_id = $del_id;
              $this->table_name = $table_name;
              if (isset($this->del_id) && is_numeric($this->del_id) && !empty($this->del_id)) {
                $sql = "DELETE FROM $this->table_name WHERE id=$this->del_id LIMIT 1";
                $del_result = mysql_query($sql);
                $aff_row = mysql_affected_rows();
                return $aff_row;
              }
            }
          
          }
          // class ends here
          
          //call class to connect to server and db as well.
          $connect = new MySQL('localhost', 'root', '');
          $connect->Database('db_name');
          ?>
          
           //include file mysql.php and call your class object as :
          
          //fetching data from any table use :
          $variable = $connect->fetch_data("SELECT * FROM table_name");
          for($i=0;$i<count($variable);$i++){
          $result = $variable[$i]['col_name'];     
          }
          //insert INTO values in any table
          $result = $connect->insert_data($tbl_name, $tbl_value);
          if($result)
          echo 'inserted';
          else{
          echo 'failed';
          }
          //delete record from any table
          $result = $connect->delete_data($del_id, $table_name)
          

          【讨论】:

            【解决方案7】:

            你可以用精彩的课ezSQL

            【讨论】:

              猜你喜欢
              • 2017-06-14
              • 2012-06-05
              • 1970-01-01
              • 1970-01-01
              • 2010-10-23
              • 1970-01-01
              • 2017-04-25
              • 2011-06-10
              • 2020-10-15
              相关资源
              最近更新 更多