【问题标题】:PHP class using mysqli使用 mysqli 的 PHP 类
【发布时间】:2015-12-26 13:40:51
【问题描述】:

我需要这样的东西。

 $mysqli = new mysqli($bd_host, $bd_user, $bd_password); 

 class webFile {

 function __construct($querystr){

 if ($result = $this->$mysqli->query($querystr)) { 

 while( $row = $result->fetch_assoc() ){ echo $row['name']; } 

 $result->close(); 

 }}}

 $object = new webFile($querystr);

我尝试了不同的变体,但有些人认为不起作用。 我对mysqli->query 感兴趣,而不是mysqli_query(a,b);

UPD 1.您的解决方案不起作用。 2. 谢谢,工作正常,DB也有问题。

【问题讨论】:

    标签: php oop mysqli


    【解决方案1】:

    您需要使用 global 让 PHP 在全局范围内查看您的 $mysqli 变量,因为这是一个全局变量,您不能使用 $this

    $mysqli = new mysqli($bd_host, $bd_user, $bd_password); 
    
    class webFile {
    
    function __construct($querystr){
    global $mysqli;
    if ($result = $mysqli->query($querystr)) { 
    
    while( $row = $result->fetch_assoc() ){ echo $row['name']; } 
    
    $result->close(); 
    
    }}}
    
    $object = new webFile($querystr);
    

    您也可以将 MySQLi 对象传递给您的构造函数并拥有一个属性:

    $mysqli = new mysqli($bd_host, $bd_user, $bd_password); 
    
    class webFile {
    
    function __construct($querystr, $conn){
    $this->mysqli = $conn;
    if ($result = $this->mysqli->query($querystr)) { 
    
    while( $row = $result->fetch_assoc() ){ echo $row['name']; } 
    
    $result->close(); 
    
    }}
    private $mysqli;
    }
    
    $object = new webFile($querystr, $mysqli);
    

    【讨论】:

      【解决方案2】:

      您也许可以这样做,将连接注入到类构造函数中。

      <?php
          $dbhost =   'localhost';
          $dbuser =   'root'; 
          $dbpwd  =   'xxx'; 
          $dbname =   'xxx';
          $oConn=new mysqli($dbhost, $dbuser, $dbpwd, $dbname);
      
          class webFile{
              private $conn;
      
              public function __construct( $conn=object, $sql=false, $field=false ){
                  if( $conn && $sql && $field ){
                      $this->conn=$conn;
                      $res=$this->conn->query( $sql );
                      if( $res ){
                          while( $rs=$res->fetch_object() ) echo $rs->$field;
                      }
                  }
              }
          }
      
      
          $obj=new webFile( $oConn, 'select * from users', 'user' );
      
      ?>
      

      【讨论】:

        猜你喜欢
        • 2012-01-09
        • 1970-01-01
        • 1970-01-01
        • 2017-09-22
        • 2013-08-26
        • 2013-08-30
        • 1970-01-01
        相关资源
        最近更新 更多