简体   繁体   English

插入查询foreach循环问题

[英]Insert query foreach loop trouble

I don't have to worry about mysql depreciation, nor SQL injections, just a personal project 我不必担心mysql的贬值,也不必担心SQL注入,而只是一个个人项目

My Code: 我的代码:

if ($_SERVER['REQUEST_METHOD'] == 'POST') { // check if the user submits data (POST) or just loads the page (GET)
$error = false;
$required = array('uexam_id', 'usubject', 'uexam_date'); //VALIDATION: first check all required fields are not empty.


foreach($required as $field) {
    if (!isset($_POST[$field]) || empty($_POST[$field])) {
        $error = true;
        break;
    }
}
//if a field was empty, show error
if ($error) {
    die("All fields required!!! <a href='examisud.php'> Back to PHP Form </a>");
} else {
    $InsertQuery = "INSERT INTO Exam (exam_id, subject, exam_date) VALUES ('".mysql_real_escape_string($_POST["uexam_id"], $con)."','".mysql_real_escape_string($_POST["usubject"], $con)."','".mysql_real_escape_string($_POST["uexam_date"], $con)."')";
    $result = mysql_query($InsertQuery, $con) or die('query Failure:'. mysql_error());
}
}

I have a superficial/aesthetic problem here. 我这里有一个肤浅的/美学的问题。 The insert/update/delete queries work fine however this foreach loop seems to be giving me trouble. 插入/更新/删除查询工作正常,但是此foreach循环似乎给我带来了麻烦。 Everytime I navigate to this page (examisud), I get the error "All fields required". 每次导航到此页面时(examisud),都会收到错误“所有必填字段”。 Except, there's not actually any error happening, it's just displaying the message. 除了,实际上没有发生任何错误,只是显示消息。 That's on page load for some reason. 由于某种原因,这在页面加载中。 Also, whenever I update or delete, the error message displays again, but the values in the fields are updated/deleted like they are supposed to. 此外,无论何时更新或删除,都会再次显示错误消息,但是字段中的值会像预期的那样被更新/删除。 It's weird, i'm hoping someone can point me the way to stopping this loop from appearing only when I need it to, which is when a field is left blank??? 太奇怪了,我希望有人能为我指出阻止该循环仅在我需要时才出现的方式,也就是当一个字段留为空白时??? Any help is much appreciated! 任何帮助深表感谢!

Try this: 尝试这个:

Your condition makes true every time on Page load. 您的条件在每次页面加载时均成立。

Remove this: if ($_SERVER['REQUEST_METHOD'] == 'POST') 删除此内容: if ($_SERVER['REQUEST_METHOD'] == 'POST')

Use this: if (!empty($_POST)) 使用这个: if (!empty($_POST))

just debug it to see which field makes your $error equals true: 只需调试它,看看哪个字段使您的$ error等于true:

foreach($required as $field) {
    if (!isset($_POST[$field]) || empty($_POST[$field])) {
        $error = true;
        echo 'Im an empty field that causes you trouble: ' . $field;
        break;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM