使用foreach循环无法删除数据库行 - php / mysql

时间:2017-03-28 17:43:18

标签: php mysql foreach

我试图从三个表中删除一些数据,

1: - 疾病 2: - jnctn_ailments_symptoms 3: - 症状

我试图首先从连接表删除链接,然后删除疾病(反之亦然),然后最终检查症状与其他疾病的任何其他链接,如果不是从症状表中删除症状。  但我在foreach循环中的步骤失败,我正在检查除了疾病旁边症状的发生。一切都很好但是当涉及到删除症状我得到mysql错误"您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以获得在''附近使用的正确语法。在第1行"。

我成功检索了症状的ID,但不是以某种方式删除查询无效。

请参阅以下代码,告诉我错误的地方。

if(isset($_GET['del']))
{
    $delID = $_GET['del'];



    $originalSymptoms="";
    $symptomO[] = array();
    echo $delID;
    $symp = "SELECT symptomID  FROM symptoms 
            INNER JOIN jnctn_ailments_symptoms
            ON jnctn_ailments_symptoms.FK_symptomID= symptoms.symptomID
            INNER JOIN ailments
            ON ailments.ailmentID = jnctn_ailments_symptoms.FK_ailmentID
            WHERE ailments.ailmentID IN ('".$delID."')";


    mysql_select_db($dbName);
    $sympRes = mysql_query($symp,$con) or die(mysql_error());

        while($symprow = mysql_fetch_assoc($sympRes))
             {
               if(empty($originalSymptoms))
               {
                $originalSymptoms = $symprow['symptomID'];
               }
                else
                {
                $originalSymptoms = $originalSymptoms.",".$symprow['symptomID']; 
                }
              }




   echo $originalSymptoms;


     $newSymptoms = explode("," , $originalSymptoms);
    foreach($newSymptoms as $symptom)
    {
    $originalSymptomsArray[] = $symptom;

    }
       echo count($originalSymptomsArray);

        $delAilment = "DELETE FROM ailments WHERE ailmentID='$delID'";
    $delAilmentResult = mysql_query($delAilment,$con) or die(mysql_error());

   $delLink = "DELETE FROM  jnctn_ailments_symptoms WHERE FK_ailmentID ='$delID'";
   $delLinkResult = mysql_query($delLink,$con) or die(mysql_error());

    foreach($originalSymptomsArray as $symptom)
    {
        echo $symptom."<br>";




        $sql2 = "SELECT * FROM jnctn_ailments_symptoms WHERE FK_symptomID=".$symptom;
        $result2 = mysql_query($sql2,$con);
        $count = mysql_num_rows($result2);
        if(!$result2 || $result2 != 0)
        {
            echo mysql_error();
            $delSymptom = false;
        }
        else
        {
            $delSymptom = true;
        }


        if($delSymptom)
        {

            $sqlDel = "DELETE FROM symptoms WHERE symptomID ='$symptom'";
            $delResult = mysql_query($sqlDel,$con)or die(mysql_error());
            if(!$delResult)
            {
                echo mysql_error();
            }
            else
            {
                echo "Symptoms Deleted!";
            }
        }




    }

我尝试过FK_symptomID =&#39; $ symotom&#39;&#34 ;; ,连接等,没有任何效果。

2 个答案:

答案 0 :(得分:0)

尝试连接所有提到的查询,如下所示

$sqlDel = "DELETE FROM symptoms WHERE symptomID ='".$symptom."'";

答案 1 :(得分:0)

以某种方式代码工作

[[ ]]

感谢您的连接建议,谢谢大家。