简体   繁体   中英

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. 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.

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. 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).

The loop after the first mysqli_query() is unnecessary. UPDATE queries produce no rows to iterate over, so that loop does nothing.

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.

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.

  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. 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. <td> should not have a name attribute. 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 :

The name of the form. In HTML 4,its use is deprecated (id should be used instead). It must be unique among the forms in a document and not just an empty string in 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. 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. So after submitting the form to a PHP script,you should do a loop to update multiple rows. When reading the select query result, however, you can use mysqli_fetch_all($result) to avoid executing queries in a loop.

I remember also getting confused quite a bit when I first started learning PHP since it can have HTML mixed in it. 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. PHP MySQLi library simply passes the queries in string representation to MySQL, so it needs to obey the MySQL rules :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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