使用类从MySQL获取多行[关闭]

问题描述 投票:-2回答:1

正如标题中所提到的,我想通过aplying类使用类从数据库中获取多行。

但问题是我只获得最后一行而不是多行。

这是我试过的代码。

班主任:

Class DoctorType {

    function DoctorType() {
        require "dbconnection.php";
        $doctor_type_query  = "SELECT user_type_detail, COUNT(user_type) AS 
    'datacount' FROM users GROUP BY user_type";
        $doctor_type_result = mysqli_query( $conn, $doctor_type_query );

        while ( $patients = mysqli_fetch_assoc( $doctor_type_result ) ) {
            $this->totalPatientsA = $patients['user_type_detail'];
            $this->totalPatientsB = $patients['datacount'];
        }
    }
}

这是我打电话的对象:

$data = new DoctorType() ;

echo $data->totalPatientsA ;
echo $data->totalPatientsB ;
php mysql
1个回答
1
投票

你的类定义有一些问题。您使用的是非常旧的样式构造函数(使用PHP5进行了删除,现在构造函数应该命名为__construct())。此外,你的构造函数还有许多不应该存在的东西,但这是一个设计问题并且超出了范围。

我将只关注OOP问题,并尝试解决您检索这些行并打印这些值的主要特定问题:

class DoctorService {

    private $totalPatientsA = [];
    private $totalPatientsB = [];

    private $conn;

    public function __construct($conn) {

       $this->conn = $conn;

    }

    function fetchPatients {

        $doctor_type_query  = "SELECT user_type_detail, COUNT(user_type) AS 
    'datacount' FROM users GROUP BY user_type";
        $doctor_type_result = mysqli_query( $this->conn, $doctor_type_query );

        while ( $patients = mysqli_fetch_assoc( $doctor_type_result ) ) {
            $this->totalPatientsA[] = $patients['user_type_detail'];
            $this->totalPatientsB[] = $patients['datacount'];
        }
    }

    public function getTotalPatientsA() {
       return $this->totalPatientsA;
    }


    public function getTotalPatientsB() {
       return $this->totalPatientsB;
    }
}

有了这个,现在db连接在你的医生类之外声明,并成为它的依赖,在构造函数上声明。

要使用它,你会做类似的事情:

// I'm assuming this defines `$conn`, this is not the cleanest approach but it works for your purposes.
require_once "dbconnection.php";

$doctor_service = new DoctorService($conn);

$doctor_service->fetchPatients();

echo implode(', ', $doctor_service->getTotalPatientsA()), "\n";
echo implode(', ', $doctor_service->getTotalPatientsB()), "\n";

首先需要你的数据库连接定义,它将$conn带入范围,并将其注入你的DoctorService类。

您调用$doctor_service->fetchPatients()以执行实际查询。

要检索患者,您可以调用每个getter,并且因为它们返回一个数组,您将结果通过implode传递,以便将其转换为字符串。

© www.soinside.com 2019 - 2024. All rights reserved.