简体   繁体   English

PHP + SQL成绩簿更新多行

[英]PHP + SQL gradebook updating multiple rows

So I've been racking my brains and searching the web for the past couple of days trying to figure this one out: I want to update multiple rows in SQL. 因此,在过去的几天里,我一直在绞尽脑汁,在网上搜索,试图弄清楚这一点:我想更新SQL中的多行。 The problem is that this database won't update. 问题是该数据库不会更新。 I know it's not a good idea to be putting SQL queries into loops, but this is the only way I've been able to get the data from the table. 我知道将SQL查询放入循环中不是一个好主意,但这是我能够从表中获取数据的唯一方法。

Here is the code: 这是代码:

    if(isset($_POST['save'])){
    $update_query = "UPDATE grades SET grade_value = '{$_POST['grade']}' WHERE user_id = 1";
    $result = mysqli_query($link, $update_query);
    while($row = mysqli_fetch_assoc($result)){
        foreach($row as $grade){
            mysqli_query($link, $update_query);
            }
         }
     }


function editGrades() { 
global $link;
$query = "SELECT * FROM grades WHERE user_id = 1";
$result = mysqli_query($link, $query);

if(!$result){
    die('Query failed' . mysqli_error());
}
while($row = mysqli_fetch_assoc($result)) {
                    $gradeValue = $row['grade_value'];
                    $gradeValue = is_array($gradeValue) ? $gradeValue : array($gradeValue);
                    foreach($gradeValue as $val){

                     ?>
                    <td name='grade'><form name="grade" method="post"><input value='<?php if (isset($val)){echo sprintf("%0.2f",$val);} ?>' type='text' class='form-control' name='grade'></td>
              <?php      }

}

} }

                <table class="table gradebook">

                <tr><th>Student</th><?php displayAssignments(); ?></tr>
                <tr><?php displayStudents();?><?php editGrades(); ?></tr>

            </table>

        <div id="btncontainer">
            <br />
        <input type="submit" method="post" name="save" action="gradebook.php" class="btn btn-success">Save Changes</button>
        </div>

My best guess as to why mysqli_query isn't updating is because there are multiple $_POST['grade'] values being submitted and SQL doesn't know what to do with them. 关于为什么不更新mysqli_query最好猜测是,因为提交了多个$_POST['grade']值,而SQL不知道如何处理它们。 I've checked the the form and input names and all of those check out fine. 我已经检查了表格和输入名称,所有这些都很好。

(I know user_id shouldn't be in the grades table, but I'm just trying to get this working and will optimize SQL queries later). (我知道user_id不应在成绩表中,但我只是想使它起作用,以后会优化SQL查询)。

The loop after the first mysqli_query() is unnecessary. 在第一个mysqli_query()之后的循环是不必要的。 UPDATE queries produce no rows to iterate over, so that loop does nothing. UPDATE查询不产生要迭代的行,因此该循环不执行任何操作。

Instead you should check for error after: 相反,您应该在以下情况下检查错误:

$result = mysqli_query($link, $update_query);

like this: 像这样:

if (!$result)
  die("Error running query:".mysqli_error($link));

It would also help in debugging if you printed the number of updated rows in case of success, eg: 如果成功打印了更新的行数,这也将有助于调试,例如:

echo("Updated rows:".mysqli_affected_rows($link));

This will help you figure out if the reason you see no updated rows is the syntax error in your query or the fact that it matched no rows. 这将帮助您确定看不到更新行的原因是查询中的语法错误还是它不匹配任何行。

You should also make sure to properly sanitize the user input (eg with mysqli_escape_string() ) to avoid SQL injection attacks. 您还应该确保正确清理用户输入(例如,使用mysqli_escape_string() )以避免SQL注入攻击。

Updating isn't working for the reason you pointed yourself: there are multiple 'grade' fields resulting in an array type of $_POST['grade'], but there are a few more things to be pointed here. 由于您自己指出的原因,更新无法正常工作:存在多个“等级”字段,导致数组类型为$ _POST ['grade'],但这里还有一些要指出的地方。

  1. <td name='grade'><form name="grade" method="post"><input ... type='text' name='grade'></td> You've set the same name attribute on 3 elements here. <td name='grade'><form name="grade" method="post"><input ... type='text' name='grade'></td>您在上设置了相同的name属性这里有3个元素。 Even though this is not a real issue and is probably not causing any problems, the name attributes are usually assigned to fields inside of a html form. 即使这不是真正的问题,并且可能不会引起任何问题,但通常会将name属性分配给html表单的字段。 <td> should not have a name attribute. <td>不应具有名称属性。 The form's name should probably be different from the text input name if you choose to have one. 如果选择一个表单名称,则名称可能与文本输入名称不同。 However <form> 's name attribute is deprecated since HTML4 according to Mozilla Foundation : 但是,根据Mozilla Foundation,自HTML4起,不推荐使用<form>name属性:

The name of the form. 表单名称。 In HTML 4,its use is deprecated (id should be used instead). 在HTML 4中,不建议使用它(应使用id代替)。 It must be unique among the forms in a document and not just an empty string in HTML 5. 它在文档中的表单之间必须唯一,而不仅仅是HTML 5中的空字符串。

  1. I'm going to guess that your grades are actually of different subjects, so you probably need a 'subject_type' column in your 'grades' table that should be assigned with foreign id's from a separate 'subjects' table to correctly utilize the relational database. 我猜您的成绩实际上是不同学科的,因此您可能需要在“成绩”表中的“ subject_type”列中分配来自单独“主题”表中的外来ID,以正确利用关系数据库。 And there are different ways to implement this on the front end. 并且有多种方法可以在前端实现这一点。 One way is that you can set the name attributes of the text fields to the different subject names instead of just 'grade'. 一种方法是,您可以将文本字段的名称属性设置为不同的主题名称,而不仅仅是“等级”。

  2. While you can do batch insert statements in SQL, there's not an equivalent syntax for update. 尽管您可以在SQL中执行批处理插入语句,但没有等效的更新语法。 So after submitting the form to a PHP script,you should do a loop to update multiple rows. 因此,在将表单提交到PHP脚本后,您应该执行循环以更新多行。 When reading the select query result, however, you can use mysqli_fetch_all($result) to avoid executing queries in a loop. 但是,在读取选择查询结果时,可以使用mysqli_fetch_all($ result)避免循环执行查询。

I remember also getting confused quite a bit when I first started learning PHP since it can have HTML mixed in it. 我记得我刚开始学习PHP时也会感到困惑,因为它可以混入HTML。 And the beginning books would have all the codes in one script. 并且开始的书将所有代码合并在一个脚本中。 The other day on SO, I saw a post where the person was assigning PHP session variables to JavaScript... It is important to keep in mind in the beginning that PHP, MySQL, HTML, JavaScript are all separate languages and each has its own syntax. 在前一天的SO上,我看到了一个帖子,该人员正在向PHP分配PHP会话变量。首先要记住,PHP,MySQL,HTML,JavaScript都是独立的语言,并且每种语言都有自己的语言。句法。 PHP MySQLi library simply passes the queries in string representation to MySQL, so it needs to obey the MySQL rules :) PHP MySQLi库只是将查询以字符串表示形式传递给MySQL,因此它需要遵守MySQL规则:)

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

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