使用类从MySQL获取多行

时间:2019-04-14 08:36:50

标签: php mysql

如标题中所述,我想通过类来使用类从数据库中获取多行。

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

这是我尝试过的代码。

班主任:

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 ;

1 个答案:

答案 0 :(得分: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;
    }
}

有了这个,现在数据库连接在Doctor类之外声明,并成为它的依赖项,并在构造函数中声明。

要使用它,您将执行以下操作:

// 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传递,因此将其转换为字符串。