MYSQL语句和用我的数据构建PHP关联数组的更简单解决方案

MYSQL语句和用我的数据构建PHP关联数组的更简单解决方案,php,mysql,Php,Mysql,我正试图获得第一次被诊断为癌症的患者的姓名和类型。 我已经设法找回了它们,但我相信一定有更简单的方法 $id = array_values(mysqli_fetch_array($conn->query("SELECT diagnosis_id from ddpt where patientnhs_no = '$nhsno' order by diagnosis_id asc limit 1")))[0]; //get the date of the first diagnosi

我正试图获得第一次被诊断为癌症的患者的姓名和类型。 我已经设法找回了它们,但我相信一定有更简单的方法

$id = array_values(mysqli_fetch_array($conn->query("SELECT diagnosis_id from ddpt where patientnhs_no = '$nhsno' order by diagnosis_id asc limit 1")))[0];

    //get the date of the first diagnosis using the diagnosis id 
    $date = array_values(mysqli_fetch_array($conn->query("select date from diagnosis where diagnosis_id ='$id'")))[0];

    //get the id of the cancer name
    $ctype_id = array_values(mysqli_fetch_array($conn->query("select ctype_id from diagnosis where diagnosis_id ='$id'")))[0];

    //get the id of the histology name
    $hname_id = array_values(mysqli_fetch_array($conn->query("select hname_id from diagnosis where diagnosis_id ='$id'")))[0];

    //get the name of the cancer type
    $cname = array_values(mysqli_fetch_array($conn->query("select name from cancertype where ctype_id ='$ctype_id'")))[0];

    //get the name of the histology 
    $ctype = array_values(mysqli_fetch_array($conn->query("select hist_name from histologynames where hname_id ='$hname_id'")))[0];

通过在查询中连接表,在一条语句中获得所需的所有内容

"select column1,column2,column3... from table1,table2,table3";

然后使用foreach和if语句进行循环。

您可以在一个查询中选择多个列,甚至可以使用
join

$query = $conn->query("SELECT diagnosis_id, date, ctype_id, hname_id, name, hist_name
               FROM ddpt
               JOIN diagnosis ON diagnosis.diagnosis_id = ddpt.diagnosis_id
               JOIN cancertype ON cancertype.ctype_id = diagnosis.ctype_id
               JOIN histologynames ON histologynames.hname_id = diagnosis.hname_id
               WHERE patientnhs_no = '$nhsno'
               ORDER BY ddpt.diagnosis_id ASC LIMIT 1");

$result = array_values(mysqli_fetch_array($query));

代码本身需要优化,但对于基本用法,这没关系。

表诊断中的3项可以在一个查询中完成。这个想法的基本原理如下:

$result = mysql_query("
    SELECT date, ctype_id, hname_id 
    FROM diagnosis 
    WHERE diagnosis_id ='$id
'");

$row = mysql_fetch_array($result, MYSQL_ASSOC)
$date = $row["date"];
$ctype_id = $row["ctype_id"];
$hname_id = $row["hname_id"];

也许有一个更简单的方法,但这是一个太广泛的要求。请阅读非常感谢,我想这就是我所期待的for@Nurettin别忘了标记为已回答,以防其他用户遇到此类问题