简体   繁体   English

将复选框值更新到数据库

[英]Update checkbox value to database

I want to update my database entry with an 1 or 0 depends on it is checked or not.我想用 1 或 0 更新我的数据库条目,这取决于它是否被检查。

My current code looks like this (only one checkbox, the others are the same just other name):我当前的代码如下所示(只有一个复选框,其他的只是其他名称相同):

<form method="post" action="" name="form">
  <label class="switch"><input type="checkbox" name="csgo" value="1"><span class="slider"></span></label> CSGO;
  <input type="submit" value="Save" class="btn btn-primary" name="submit">
 <?php
   $csgoac = isset($_POST["csgo"]) ? $_POST["csgo"] : 0;
   $sql = "UPDATE Users SET csgoactive='".$csgoac."' WHERE ID='1'";
   mysqli_query($db, $sql);
 ?>
</form>

I tested it with echo $csgoac;我用echo $csgoac;测试了它echo $csgoac; (before the query) and the output was checked = 1 and not checked = 0 . (在查询之前)并且输出被checked = 1和未checked = 0

With the query now, it is only updating "0" to the database, what I did wrong on there?现在使用查询,它只是将“0”更新到数据库,我在那里做错了什么?

Of course, the first time the page is rendered, $csgoac is 0 because isset($_POST["csgo"]) is false.当然,第一次渲染页面时, $csgoac为0,因为isset($_POST["csgo"])为false。

If the checkbox is checked and then the form is submitted, $csgoac will be 1.如果选中复选框然后提交表单, $csgoac将为 1。

So the question becomes: What is the result of mysqli_query($db, $sql);那么问题就变成了: mysqli_query($db, $sql);的结果是什么? ? ?

Are you getting/checking all available feedback?您是否正在获取/检查所有可用的反馈? If display_errors is Off in php.ini, there will not be feedback in the browser, but perhaps an error is in the php errorlog.如果php.ini中display_errors为Off,浏览器不会有反馈,但可能是php错误日志有错误。 (For instance, in the snippet, $db is not defined, so mysqli_query($db, $sql); fails with Undefined variable: db .). (例如,在代码片段中, $db未定义,因此mysqli_query($db, $sql);失败并显示Undefined variable: db .)。

If the UPDATE is not successful, mysqli_query($db, $sql);如果UPDATE不成功, mysqli_query($db, $sql); will return FALSE and $db->error should tell you what error was encountered.将返回FALSE并且$db->error应该告诉你遇到了什么错误。

You could also use mysqli_stmt_affected_rows for additional feedback.您还可以使用mysqli_stmt_affected_rows获得额外的反馈。

Perhaps add some feedback/error checking to get as much information as possible so you can know what is really happening.也许添加一些反馈/错误检查以获取尽可能多的信息,以便您了解实际发生的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM