[英]Adding to a value in a table on the press of a button on a webpage?
我對SQL非常陌生,至少可以說,我在努力。
我的桌子看起來像這樣:
我要做的就是只要按下一個按鈕就可以將這些值中的任何一個加1,如下所示:
這就是它在網站上的外觀,但是根本沒有任何功能。
我對HTML,CSS和PHP有所了解,因此,如果我想知道使用SQL進行此操作的正確方法,則應該能夠實現它。
謝謝。
一種方法是在發送表單時使用AJAX來調用處理mysql查詢並“添加一個”的php腳本。 您應該在隱藏的輸入中輸入要增加的人的名字。 那就是如果您不想刷新頁面。
如果您不介意刷新,請使每個按鈕成為表單的一部分,然后發送到相同的php文件。
最近,我遇到了一個名為meteor.js的庫,它能夠完成所有這些工作。 我還沒有測試過。
好的,我看到有人建議使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.