【问题标题】:Create a fetch query in a file and show it in another file在一个文件中创建一个 fetch 查询并在另一个文件中显示它
【发布时间】:2023-03-17 18:16:01
【问题描述】:

我对 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>'; 
    }

【问题讨论】:

    标签: php mysql oop


    【解决方案1】:

    在 OOP 中,您有一个构造函数,可以通过在实例化该对象时建立该连接来帮助您,这样您就不必在每个查询中使用 $this-&gt;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-&gt;$dataObject = $result;

    还有一个可以调用来返回变量的公共函数。

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

    【讨论】:

      猜你喜欢
      • 2017-11-30
      • 1970-01-01
      • 2013-09-20
      • 2020-09-05
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多