[英]update database with checkbox
My database table has 2 fields: id
(int) and state
(enum -> 0,1). 我的数据库表有2个字段: id
(int)和state
(枚举-> 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). 我需要做的是使用checkbox
的状态更新数据库(我的state
字段)( 0
表示空白, 1
表示选中)。
To show each of the fields in my database, I use a loop: 为了显示数据库中的每个字段,我使用一个循环:
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
}
?>
My update file: 我的更新文件:
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++;
}
Where I need help is the AJAX part of the code. 我需要帮助的地方是代码的AJAX部分。 I'm guessing it looks something like this, but it doesn't seem to work: 我猜它看起来像这样,但似乎不起作用:
AJAX 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. 我一直在环顾四周,看到了一些可以使用“提交”按钮执行此操作的示例,但是没有一个单击复选框时会自动记录信息的示例。
Try this: 尝试这个:
AJAX 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);
}
}
Changed 3 things: 更改了3件事:
$("onoffswitch-checkbox")
so its now $(".onoffswitch-checkbox")
在$("onoffswitch-checkbox")
添加了一个点,因此其现在$(".onoffswitch-checkbox")
id=
after module_update.php?
在module_update.php?
之后添加了id=
module_update.php?
and before id
value. 以及id
值之前。 state
also I added that also with a &
to separate the values for $_GET
in php to separate them 因为您还需要state
所以我还添加了&
来分隔php中$_GET
的值以分隔它们 PHP PHP
I don't know what you mean with $_GET['onoffswitch-checkbox']
in the php, maybe a mistake? 我不知道您在php中使用$_GET['onoffswitch-checkbox']
是什么意思,也许是错误的? My suggestion does not need it anyway, neither does your mysql query. 我的建议无论如何都不需要它,您的mysql查询也不需要。
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: 由于您一次只会单击一个,因此我认为不需要php中的foreach
循环,因此您可以这样做:
$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++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.