首页 文章

在文件中创建提取查询并将其显示在另一个文件中

提问于
浏览
-1

我对PHP和MySQL的OOP有疑问 .

我正在使用OOP使用PHP 7,我想创建一个类Connection . 在这些课堂上
我有一个方法,可以生成对数据库的查询并将其存储在数组中 . 我希望该数组的结果在另一个文件的另一个类中打开 . 如果我使用if语句,则发送一个值,如果我使用while循环,当我在另一个文件中请求向量时,不会显示任何内容 . 我想创建此方法,以避免重写与数据库连接的调用 .

这是将继承显示数据的类的代码 .

public function open_connection()
{ 
    $this->connect = new mysqli( self::$SERVER, self::$USER, self::$PASS, $this->DB ) or die ( "Error" ); 
} 

public function close_connection()
{ 
    mysqli_close( $this->connect ); 
}

protected function execute_a_fetch_query( )
{
    $this->open_connection();
    $orderA = $this->connect->query( $this->query );
    $orderB = $this->connect->query( $this->query );
    if ( $this->rows = mysqli_fetch_array( $orderA ) ) { //this sentence avoid a duplicate result from the query
        if ( $this->rows = mysqli_fetch_array( $orderB ) );
    }
    $this->close_connection();
}

这是Show类中的另一个方法

public function data( $attributes = array() )
{
    $this->query = 'select * from Supplier';
    $this->execute_a_fetch_query();

    echo '<tr>';

    for ( $i = 0; $i < count( $this->_attributes ); $i++ ) {
        echo 
            '<td>'. $this->rows[ $attributes[ $i ] ]. '</td>'; 
    }

1 回答

  • -1

    在OOP中,您有一个构造函数,可以在实例化该对象时通过 Build 该连接来帮助您,这样您就不必在每个查询中使用 $this->open_connection(); .

    而不是创建一个 open_connection() 函数使用

    function __ construct(){
      $this->connect = new mysqli( self::$SERVER, self::$USER, self::$PASS, $this->DB ) or 
        die ( "Error" );
     }
    

    所以 $obj = new BaseClass(); 会打开一个连接 .

    你也可以在同一个类中拥有一个私有变量

    private $dataObject 可在您的查询中设置 $this->$dataObject = $result;

    和一个可以调用以返回变量的公共函数 .

    public function getData()
    {
      return $this->$dataObject;
    }
    

相关问题