【问题标题】:How can I update a specific record in a sql database based on a selection made in a dropdown select box?如何根据下拉选择框中的选择更新 sql 数据库中的特定记录?
【发布时间】:2015-10-23 21:43:25
【问题描述】:

好的,我在这上面花了几天时间,但我已经超出了我的深度。我承认我对 sql、jquery 和 ajax 完全陌生。我为此提前道歉。

我正在尝试构建一个应用程序,管理员可以在其中查看用户一段时间内的表现,平均过去 2 周的输入分数。使用下拉框应该从数据库中选择一个成员(这部分似乎有效),然后可以填写下面的表格并按下“更新”按钮来更新数据库中的记录(这完全被破坏了)。

选择框是使用 ajax 从数据库中填充的,我可以使用 onchange 函数从选择中返回值,但是当我尝试使用我的表单更新数据库时,什么都没有更新。

插入按钮和相关代码正常工作,信息正确存储在数据库中。 (当我的代码正确时,我会将数据分成更准确的表格,因为我不想在挣扎时处理联接和多个表格。)

从选择菜单中选择名称时,$_POST['memberID'] 会显示正确的数字。

在表单中输入信息并按下“更新”后,$_POST['memberID'] 为空白且数据库不会更新。

Controller.php:

<?php require 'php/dbconnect.php';
$records = array();
if(!empty($_POST)) {
    switch (true) {
        case isset($_POST['insert']):
            if(isset($_POST['name'], $_POST['designation'], $_POST['rank'], $_POST['currentScore'])) {
                // The following trim functions followed by !empty ensures that a series of spaces is not accepted from users as input.
                $name = trim($_POST['name']);
                $designation = trim($_POST['designation']);
                $rank = trim($_POST['rank']);
                $currentScore = trim($_POST['currentScore']);

                if(!empty($name) && !empty($designation) && !empty($rank) && !empty($currentScore)) {

                    $insert = $conn->prepare("INSERT INTO members (name, designation, rank, currentScore) VALUES (?,?,?,?)");
                    $insert->bind_param('ssii' , $name, $designation, $rank, $currentScore);

                    if($insert->execute()) {
                        $insert->free(); //Remove Query Data from memory since it is no longer needed.
                        header('location: index.php');
                        die();
                    }
                }
            }
        break;

        case isset($_POST['update']):
            $name = trim($_POST['name']);
            if(!empty($name)) {
            $update = $conn->prepare("UPDATE members SET name = ? WHERE '$memberID'");
            $update->bind_param('s', $name);
                if($update->execute()) {
                        header('location: index.php');
                        die();
                    }
            }
        break;

//      case isset($_POST['delete']):
//          // Delete statement goes here
//      break;
//      else 
    }
}
if($results = $conn->query("SELECT *, ((previousScore + currentScore) / 2) AS avgScore FROM members")) {
    if($results->num_rows) {
        while($row = $results->fetch_object()) {
            $records[] = $row; //Appending value to array
        }
        $results->free();
    }
}
?>

索引.php:

<?php include 'header.php' ?>
     <?php if(!count($records)) {
        echo 'No Records' ;
     } else {
     ?>
    <form id="memberSelect" method="post">
        <select name="memberID" id="members" onchange="change()">
            <!-- Populated with function members in footer.php -->
        </select>
    </form>
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Designation</th>
                    <th>Rank</th>
                    <th>Previous Score</th>
                    <th>Current Score</th>
                    <th>Average Score</th>
                </tr>
            </thead>
            <tbody>
                <?php
                foreach($records as $r) {
                ?>

                <tr>
                    <td><?php echo escape($r->name); ?></td>
                    <td><?php echo escape($r->designation); ?></td>
                    <td><?php echo escape($r->rank); ?></td>
                    <td><?php echo escape($r->previousScore); ?></td>
                    <td><?php echo escape($r->currentScore); ?></td>
                    <td><?php echo escape($r->avgScore); ?></td>
                    <!-- Remember when putting data in that current score needs to be moved to previous score's
                    position and the NEW score will take the place of current score(which will be the old score until updated) -->
                </tr>
                <?php 
                }
                ?>
            </tbody>
        </table>
    <?php
    }
    ?>

    <hr>

    <form action="" method="post">
        <div class="field">
            <label for="name">Member name</label>
            <input type="text" name="name" id="name" autocomplete="off">
        </div>
        <div class="field">
            <label for="designation">Designation</label>
            <input type="text" name="designation" id="designation" autocomplete="off">
        </div>
        <div class="field">
            <label for="rank">Rank</label>
            <input type="text" name="rank" id="charLevel" autocomplete="off">
        </div>
        <div class="field">
            <label for="currentScore">Current Score</label>
            <input type="text" name="currentScore" id="currentScore" autocomplete="off">
        </div>
        <div id="submit">
            <!-- Add a comment section to be input into DB -->
            <input type="submit" name="insert" value="Insert">
            <input type="submit" name="update" value="Update">
            <input type="submit" name="delete" value="Delete">
            <!-- <input type="hidden" name="id" value="<?php //echo $?>"> -->
        </div>
    </form>
<?php include 'footer.php' ?>

页脚.php:

</div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.3.min.js"><\/script>')</script>
        <script src="js/plugins.js"></script>
        <script src="js/main.js"></script>
        <script>
            //How do you explain something you barely understand? The following function uses JQUERY
            //json, and ajax to fill a select dropdown with items populated from a linked database.
            //See the jsonData.php for the json data being referenced here, it is imperitive to the operation of
            //this function that json data be available.
            function members(){
                $('#members').empty();//Removes all content of the associated ID 'members' to ensure a clean default value
                $('#members').append("<option>Loading</option>");//fill them with a default message
                $.ajax({
                    type:"POST",
                    url:"php/jsonData.php",//the location of the json data, for this it is required to be in its own file
                    contentType:"application/json; charset=utf-8",
                    dataType: "json",
                    success: function(records){ //only fires if the json data is found
                        $('#members').empty();//If everything is ok, removes previous default value
                        $('#members').append("<option value='0'>--Select Member--</option>");
                        $.each(records,function(i,memberID){//Uses a foreach loop to fire a function for every memberID, assigning the value to i
                            $('#members').append('<option value="'+ records[i].memberID +'">'+ records[i].name +'</option>');
                            //^ The workhorse. Grabs the select value by the ID, appends the option value by looking within the records array
                            //(which is defined and assigned values in the jsonData.php file) and assigns the member id as the value and the 'name'
                            //as the option. This populates the dropdown with the names and gives them the value 'memberID' from the database.
                        });
                    },
                    complete: function(){
                     }
                });
            }
            $(document).ready(function(){
                members();
            });
        </script>
        <script>
            function change(){
                $('#memberSelect').submit();//Submits the page to the server when called
            }
        </script>

        <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
        <script>
            (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
            function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
            e=o.createElement(i);r=o.getElementsByTagName(i)[0];
            e.src='https://www.google-analytics.com/analytics.js';
            r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
            ga('create','UA-XXXXX-X','auto');ga('send','pageview');
        </script>
    </body>
</html>

【问题讨论】:

  • 你真的不能缩小范围吗?
  • 每当我看到这样的问题时,我总想大喊把它分解成两个独立的问题,单独解决。你有两个问题让你的表单正常工作(不需要mysql)。然后你必须弄清楚如何根据一些 php 变量更新 ea mysql 行。 Javascript 和 html 与此无关。
  • 感谢您的提示,我很感激,我会继续努力解决这个问题。我的问题是我无法弄清楚出了什么问题,这需要时间让我弄清楚。 @e4c5 我也想大喊大叫。已经好几天了,我知道这些是基本级别的问题。
  • 编程就像吃一头大象,你需要一次解决一个小问题,然后大问题就解决了。

标签: javascript php jquery mysql ajax


【解决方案1】:

我认为问题出在更新块的这一行:

$update = $conn->prepare("UPDATE members SET name = ? WHERE '$memberID'");

我假设您的成员表的主键是:member_id

那么这段代码将是:

$update = $conn->prepare("UPDATE members SET name = ? WHERE member_id = ?");
$update->bind_param('si', $name, $memberID);

试试这个。希望对您有所帮助。

【讨论】:

  • 我遇到了几个问题,这是其中之一。这段代码完美运行,对我帮助很大。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 2015-04-21
相关资源
最近更新 更多