用复选框更新数据库 [英] update database with checkbox
问题描述
我的数据库表有2个字段: id
(int)和 state
(enum - > 0,1) 。
My database table has 2 fields: id
(int) and state
(enum -> 0,1).
我需要做的是用状态a更新我的数据库(我的州
字段) code>复选框( 0
表示空, 1
表示已选中)。
What I need to do is to update my database (my state
field) with the state of a checkbox
(0
for empty, 1
for checked).
要显示我的数据库中的每个字段,我使用循环:
To show each of the fields in my database, I use a loop:
循环:
<?php
foreach ( $posts_array as $module )
{
?>
<h2><?php echo $module->titre; ?></h2>
<input type="checkbox" name="chkbx_<?php echo $module->id; ?>"> id="chkbx_<?php echo $module->id; ?>" class="onoffswitch-checkbox"> On/Off <br />
<?php
}
?>
我的更新文件:
foreach ($_GET['onoffswitch-checkbox'] as $id => $state)
{
// $_GET['onoffswitch-checkbox'] = class for all my checkboxed
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;
}
我需要帮助的地方是代码的AJAX部分。我猜它看起来像这样,但它似乎不起作用:
Where I need help is the AJAX part of the code. I'm guessing it looks something like this, but it doesn't seem to work:
AJAX
$(document).ready(function() {
$("onoffswitch-checkbox").click(function() {
var id = $(this).attr('id');
$("#state_span").load("module_update.php?"+id);
}
}
我一直在环顾四周,看了几个例子,我们可以通过提交按钮这样做,但是没有在单击复选框时自动记录信息的地方。
I've been looking around, seen a few examples where the we could do so with a submit button, but none where the information is automatically recorded when clicking the checkbox.
推荐答案
试试这个:
AJAX
$(document).ready(function() {
$(".onoffswitch-checkbox").click(function() {
var id = this.id; //changed here also, just because jQuery is not needed here
var state = this.checked ? 1 : 0;
$("#state_span").load("module_update.php?id="+id+"&state="+state);
}
}
更改了3件事:
- 在
$(onoffswitch-checkbox)
中添加了一个点,所以它现在$(。onoffswitch-checkbox)
- 在<$ c $之后添加
id =
c> module_update.php?之前id
value。 - 因为你需要
州
我还添加了&
来分隔$ _ GET
在php中将它们分开
- added a dot in
$("onoffswitch-checkbox")
so its now$(".onoffswitch-checkbox")
- added
id=
aftermodule_update.php?
and beforeid
value. - since you need
state
also I added that also with a&
to separate the values for$_GET
in php to separate them
PHP
我不知道你在php中使用 $ _ GET ['onoffswitch-checkbox']
是什么意思,也许是个错误?我的建议无论如何都不需要它,你的mysql查询也没有。
I don't know what you mean with $_GET['onoffswitch-checkbox']
in the php, maybe a mistake? My suggestion does not need it anyway, neither does your mysql query.
因为你一次只点击一个我认为不需要 foreach
在php中循环,所以你可以这样做:
Since you will be only clicking one at a time I see no need for the foreach
loop in php, so you could do this:
$id = $_GET['id'];
$state= $_GET['state'];
// $_GET['onoffswitch-checkbox'] ?? I don't think you need this...
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;
这篇关于用复选框更新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!