用于更新数据库条目的多个if语句

时间:2017-05-27 12:48:13

标签: php mysql if-statement

让按钮点击下面的代码转到名为'college'的数据库,其中列名为'college1','college2'等(到'college10')以及'sports1','sports2'等(到'sports10')

if ($row['college4'] == null) {
     $sql = "UPDATE colleges SET college3 = NULL, sports3 = NULL";
}
if ($row['college3'] == null) {
     $sql = "UPDATE colleges SET college2 = NULL, sports2 = NULL";
}
if ($row['college2'] == null) {
     $sql = "UPDATE colleges SET college1 = NULL, sports1 = NULL";
}

实质上,如果数据库中的特定列等于NULL,则将前一列设置为NULL。然而,先前的编码仅适用于最近的if语句(在本例中为college2)。一旦执行,剩余的if语句将被忽略(即大学4和大学3。

如果需要更多解释,请告诉我。我想我只是在寻找如何让sql查询以级联方式识别。谢谢。

完整的PHP:

<?php
            session_start();

            define("DB_HOST", "");
            define("DB_USER", "");
            define("DB_PASS", "");
            define("DB_NAME", "");

            // Create connection
            $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            }

                    if ($row['college4'] == null) {
                        $sql = "UPDATE colleges SET college3 = NULL, sports3 = NULL";
                    }
                    if ($row['college3'] == null) {
                        $sql = "UPDATE colleges SET college2 = NULL, sports2 = NULL";
                    }
                    if ($row['college2'] == null) {
                        $sql = "UPDATE colleges SET college1 = NULL, sports1 = NULL";
                    }

            if ($conn->query($sql) === TRUE) {
                echo "Record deleted successfully";
            } else {
                echo "Error deleting record: " . $conn->error;
            }

            mysqli_close($conn);
        ?>

2 个答案:

答案 0 :(得分:3)

您的所有更新都缺少WHERE条款,并使用ANDOR作为分隔符,而不是逗号posted in comments

UPDATE colleges SET college3 = NULL, sports3 = NULL 
WHERE college3 != NULL, sports3 != NULL

应为:

UPDATE colleges SET college3 = NULL, sports3 = NULL 
WHERE college3 != NULL AND sports3 != NULL

或使用OR逻辑运算符,具体取决于条件。

另外,正如我在评论中提到的那样;您正在更新整个数据库而没有WHERE子句。

参考手册:

答案 1 :(得分:0)

$max = 4; // set maximum number of College 

$sql = '';
for($i=$max; $i>=2; $i--) {
    if($row['college'.$i] == null) {
        $sql .= "UPDATE colleges SET college".($i-1)." = NULL, sports".($i-1)." = NULL;";
    }
}

在这种情况下,您必须在for循环后运行查询。您也可以在if语句中运行。然后代码将是:

$max = 4; // set maximum number of College

for($i=$max; $i>=2; $i--) {
    if($row['college'.$i] == null) {
        $sql = "UPDATE colleges SET college".($i-1)." = NULL, sports".($i-1)." = NULL";
// Query Run Code Here
    }
}