对循环中

时间:2017-01-05 20:33:46

标签: php mysqli

我正在尝试设计一个系统,可以根据用户输入的内容来诊断疾病的用户。我使用jquery创建动态文本框,用户在其中键入症状。这存储在数组中并传递到php文件运行查询结果。

<?php
$symp=$_POST['fields'];
foreach ($symp as $Values) {
$qry=   "SELECT D.name, group_concat( symp SEPARATOR ',' ) as conca, count(*) as SymptomsMatching from linkds DS JOIN symptoms S on DS.symptomId = S.id JOIN disease D on DS.diseaseId = D.id WHERE  S.symp  IN ('$Values') GROUP BY D.name ORDER BY count(*) DESC, D.name ";
$rep=mysqli_query($con,$qry);
  foreach ($rep as $row) {
  echo"<tr>
  <td class='text-left'>".$row['name']."</td>
  <td id='title'class='text-left'>".$row['conca']."</td>
  <td class='text-left'>".$row['SymptomsMatching']."</td>
  </tr>";
    }
 }

这是php脚本中的代码。目前我得到的结果却没有按疾病名称分组。

Disease     |       Symptoms        | No of Symptoms
 Malaria    |     fever             |    1
Diarrhea    |     fever             |    1
Malaria     |     nausea            |    1
Diarrhea    |     nausea            |    1
Malaria     |     headache          |    1

这个结果我现在得到了......但下表是我的期望:

Disease     |            Symptoms                   | No of Symptoms
 Malaria    |     fever,nausea,headache             |    3
Diarrhea    |     fever,nausea                      |    2

当我在phpmyadmin中运行相同的查询时,我得到正确的表...我不知道php脚本中的循环是否导致它...有人可以帮助我。

1 个答案:

答案 0 :(得分:1)

array_walk函数将帮助您正确格式化 $ values ,因此每个值都包含在“单引号”中,MYSQL WHERE IN ()将正确处理。

<?php
$symp=$_POST['fields'];

array_walk($symp, function(&$v,$k){
      $v = "'$v'";
 });

$values=implode(",",$symp);

$qry = "SELECT D.name, group_concat( symp SEPARATOR ',' ) as conca, count(*) as SymptomsMatching from linkds DS 
   JOIN symptoms S on DS.symptomId = S.id 
   JOIN disease D on DS.diseaseId = D.id 
   WHERE  S.symp  IN ($values) 
   GROUP BY D.name 
   ORDER BY SymptomsMatching DESC, D.name ASC";

$rep=mysqli_query($con,$qry);
if($rep){
    foreach ($rep as $row) {
        echo"<tr>
          <td class='text-left'>".$row['name']."</td>
          <td id='title'class='text-left'>".$row['conca']."</td>
          <td class='text-left'>".$row['SymptomsMatching']."</td>
          </tr>";
    }
}
?>