如何从数据库中提取数据并分配给变量以进行删除查询

时间:2015-08-15 19:39:27

标签: php sql

我正在尝试从数据库中提取数据然后将返回的结果分配给变量以进行另一次搜索/删除,但我不断收到一条错误消息,说明我设置的变量($ islecturer和$ group )未定义。如果有人能告诉我我在哪里出错了,我将非常感激。

<?php

require ('mysqli_connect.php');

        $q1 = "SELECT `islecturer` FROM `participants` WHERE `uninum` = 'A17'";
        $result1 = @mysqli_query($dbcon,$q1);


while ($row1 = mysqli_fetch_array ($result1, MYSQLI_ASSOC)){
       $islecturer = $row1['islecturer'];

       echo $islecturer;

}


       if ($islecturer == 0){

        $q2 = "SELECT `groupid` FROM `groups` WHERE `uninum` = 'A17'";
        $result2 = @mysqli_query($dbcon,$q2);

      }  

while ($row2 = mysqli_fetch_array ($result2, MYSQLI_ASSOC)){
       $group = $row2['groupid'];

       echo $group;

}

         $q3 = "DELETE FROM `schedule` WHERE `groupid` = $group LIMIT 1;";
            $result3 = mysqli_multi_query ($dbcon , $q3);
         $q3 .="DELETE FROM `groups` WHERE `groupid` = $group LIMIT 1;";
            $result3 = mysqli_multi_query ($dbcon , $q3);
         $q3 .="DELETE FROM `individualavailability` WHERE uninum = 'A17' LIMIT 1;";
            $result3 = mysqli_multi_query ($dbcon , $q3);
         $q3 .="DELETE FROM `availabilityindex` WHERE `uninum` = 'A17' LIMIT 1;";
            $result3 = mysqli_multi_query ($dbcon , $q3);
         $q3 ="DELETE FROM `participants` WHERE `uninum` = 'A17' LIMIT 1;";
            $result3 = mysqli_multi_query ($dbcon , $q3);


         if (mysqli_affected_rows($dbcon ) > 1) { // If it ran OK.
            echo 'Successfully deleted';
         }

        else if ($islecturer == 1){ 
        echo 'you can\'t delete a lecturer without adding a replacement group member';
        }
        else{
            echo 'query failed';
        }


mysqli_close($dbcon );

?>

1 个答案:

答案 0 :(得分:1)

$islecturer$group变量在另一个范围内定义,即在其while循环的范围内。在while循环之外,您无法再访问它们了。

while ($row1 = mysqli_fetch_array ($result1, MYSQLI_ASSOC)){
       $islecturer = $row1['islecturer'];
       echo $islecturer;
} 
// Out of scope, $islecturer is not accessible anymore

编辑:要解决此问题,您可以在循环之前定义变量。

$islecturer = 0;
while ($row1 = mysqli_fetch_array ($result1, MYSQLI_ASSOC)){
       $islecturer = $row1['islecturer'];
       echo $islecturer;
}

if ($islecturer == 0){
   ...
}

请注意,通过一些研究,您会发现this链接与您面临的问题几乎完全相同。