我是 SQL 的新手,至少可以说,我很吃力。
我的表格是这样的:
我想要做的就是能够在按下按钮时将这些值中的任何一个递增,如下所示:
这是它在网站上的样子,但还没有任何功能。
我了解 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/