【发布时间】:2016-08-20 06:05:44
【问题描述】:
我可以通过 ajax 的一个复选框值 0/1 更新 mysql 数据库,但我不知道如何使用多个复选框来执行此操作,
我的代码:index.php
<?php
$query=mysql_connect("localhost","root","root");
mysql_select_db("gpio",$query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Checkbox Switches DevGrow.com</title>
<script type="text/javascript"src="jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#switch1').click(function(){
var myonoffswitch=$('#switch1').val();
if ($("#switch1:checked").length == 0)
{
var a="1";
}
else
{
var a="0";
}
$.ajax({
type: "POST",
url: "ajax.php",
data: "value="+a ,
success: function(html){
$("#display").html(html).show();
}
});
});
});
</script>
</head>
<body>
<input type="checkbox" name="switch1" id="switch1"
<?php
$query3=mysql_query("select pinDescription from pindescription where pinID=1");
$query4=mysql_fetch_array($query3);
if($query4['pinDescription']=="0")
{
echo "checked";
}
?> >
</body>
</html>
ajax.php
<?php
$query=mysql_connect("localhost","root","root");
mysql_select_db("gpio",$query);
if(isset($_POST['value']))
{
$value=$_POST['value'];
mysql_query("update pindescription set pinDescription='$value' where pinID='1'");
}
?>
上面的代码只对一个复选框起作用,对于 8 或 10 个复选框怎么办。
<input type="checkbox" name="switch1" id="switch1"
<?php
$query3=mysql_query("select pinDescription from pindescription where pinID=1");
$query4=mysql_fetch_array($query3);
if($query4['pinDescription']=="0")
{
echo "checked";
}
?> >
<input type="checkbox" name="switch2" id="switch2"
<?php
$query3=mysql_query("select pinDescription from pindescription where pinID=2");
$query4=mysql_fetch_array($query3);
if($query4['pinDescription']=="0")
{
echo "checked";
}
?> >
<input type="checkbox" name="switch3" id="switch3"
<?php
$query3=mysql_query("select pinDescription from pindescription where pinID=3");
$query4=mysql_fetch_array($query3);
if($query4['pinDescription']=="0")
{
echo "checked";
}
?> >
在哪里更改 switch1 switch2 switch3 的脚本。
【问题讨论】:
-
您的 sql 容易受到 mySql 注入的攻击。使用 PDO。
-
更不用说旧语法了
-
@bub ,你能告诉我如何处理 PDO 吗?
-
请stop using
mysql_*functions。 These extensions 已在 PHP 7 中删除。了解PDO 和 MySQLi 的 prepared 语句并考虑使用 PDO,it's really pretty easy。
标签: php jquery mysql ajax checkbox