php - 按网页上的按钮添加到表格中的值?

标签 php mysql sql forms

我是 SQL 的新手,至少可以说,我很吃力。

我的表格是这样的:

enter image description here

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

enter image description here 这是它在网站上的样子,但还没有任何功能。

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

谢谢。

最佳答案

好吧,我看到有人建议使用 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>

关于php - 按网页上的按钮添加到表格中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25682160/

相关文章:

php - php F3框架中使用ORM Axon的select语句

php - 使用单个查询更新时自动增量 MySQL 列字段

sql - PostgreSQL 中不稳定的索引查询性能

php - 如何获得当前时间和 eventTime 之间的时差

php - Laravel 5.1 Eloquent 多对多关系

php - 比较mysql中的日期,其中日,月和年分别存储

javascript - 创建 Node.js + socket.io 服务器/客户端,进行用户身份验证、发送/接收数据

mysql - 在 mysql 中连接来自 blob 的二进制数据

javascript - 为什么 Wordpress 无法加载资源?它表示服务器响应状态为 404(未找到)

php - 使用 Codeigniter 3.0.1 在数据库中上传图像