【问题标题】:Adding to a value in a table on the press of a button on a webpage?按下网页上的按钮添加到表格中的值?
【发布时间】:2014-09-05 09:00:59
【问题描述】:

我对 SQL 很陌生,至少可以说,我很挣扎。

我的桌子是这样的:

我想要做的就是能够在按下按钮时将这些值中的任何一个递增一个,如下所示:

这是它在网站上的外观,但还没有任何功能。

我了解 HTML、CSS 和 PHP,所以如果我知道使用 SQL 执行此操作的正确方法,我应该能够实现它。

谢谢。

【问题讨论】:

    标签: php mysql sql forms


    【解决方案1】:

    好的,我看到有人建议使用 AJAX(“其他地方”以及此处),但您对此并不熟悉。我将建议一个完全非 Javascript 的解决方案,坚持使用 HTML、PHP 和 MySQL,正如您已经知道的那样。不过,我肯定会建议在某个时候学习 Javascript。

    我不知道你的理解程度,所以请让我知道你不遵循的以下代码,我会更详细地解释。

    <?php
    
        /* Initialise the database connection */
        $db = new mysqli("localhost", "username", "password", "database");
        if ($db->connect_errno) {
            exit("Failed to connect to the database");
        }
    
        /* First, check if a "name" field has been submitted via POST, and verify it 
         * matches one of your names.  This second part is important, this
         * will end up in an SQL query and you should NEVER allow any unchecked 
         * values to end up in an SQL query.
         */
        $names = array("Anawhata","Karekare","Muriwai","Piha","Whatipu");
    
        if(isset($_POST['name']) && in_array($_POST['name'], $names)) {
    
            $name = $_POST['name'];
    
            /* Add 1 to the counter of the person whose name was submitted via POST */
            $result = $db->query("UPDATE your_table SET counter = counter+1 WHERE name = $name");
            if(!$result) {
                exit("Failed to update counter for $name.");
            }
    
        }
    ?>
    
    <table>
    
    <?php
        /* Get the counters from the database and loop through them */
        $result = $db->query("SELECT name, counter FROM your_table");
        while($row = $result->fetch_assoc()) {
    ?>
    
        <tr>
            <td>
                <p><?php echo $row['name'];?></p>
    
                <form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
                    <input type="hidden" name="name" value="<?php echo $row['name']; ?>" />
                    <input type="submit" name="submit" value="Add One" />
                </form>
            </td>
    
            <td><?php echo $row['counter']; ?></td>
        </tr>
    
    <?php
    
        } // End of "while" each database record
    
    ?>
    
    </table>
    

    【讨论】:

      【解决方案2】:

      一种方法是在发送表单时使用 AJAX 来调用处理 mysql 查询并“添加一个”的 php 脚本。您应该使用要增加的人的姓名放置一个隐藏的输入。那是你不想刷新页面。

      如果你不介意刷新,让每个按钮成为表单的一部分,然后发送到同一个 php 文件。

      我最近遇到了一个名为 meteor.js 的库,它能够完成所有这些工作。不过,我还没有测试过。

      【讨论】:

      • 您有任何示例代码来演示这一点吗?就像调用 PHP“函数”的 AJAX 部分,以及我用来向列添加一个的 SQL 语句一样?谢谢
      猜你喜欢
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      相关资源
      最近更新 更多