首页 > 解决方案 > 如何通过MYSQL在按钮单击上切换布尔值

问题描述

我正忙着做一个实验。我正在尝试回显 10 个按钮,每个按钮都指向一个 id 和一个布尔值(phpmyadmin 中的 2 行)。我希望每个按钮在按下时通过布尔值反转颜色。(如果为真,按钮变为黑色,如果为假,则按钮为白色)。最重要的是,我想要一个 ajax Htmlrequest,以便您可以实时查看更改。

我希望回显的按钮通过单击按钮的功能来反转颜色。这应该通过一个从数据库获取数据的 xml httprequest。

* 编辑 *

我试图在我处理代码的问题中更准确,它仍然不起作用,但我觉得它越来越接近了。


日志.php


 $con= mysqli_connect("localhost","test","") or die ("Could not connect to MySQL!");
 mysqli_select_db($con, "buttons") or die ("Database not found!");

 $result1 = $con->query("SELECT * FROM buttons ORDER by id DESC");

 while ($extract = mysqli_fetch_array($result1))
 {
     if($extract['bool'] = true){
        echo "<form name='form1' mehod='POST'>
  <input type='button' name='btn' class='$id' href='#' style='background-color:black;' onclick='submitbtn()'/><br />
  </form>
        ";
    } else{
        echo "<form name='form1' mehod='POST'>
  <input type='button' name='btn' class='$id' href='#' style='background-color:white;' onclick='submitbtn()'/><br />
  </form>
        ";

    }

 }
?>

插入.php



 $con= mysqli_connect("localhost","test","") or die ("Could not connect to MySQL!");
 mysqli_select_db($con, "buttons") or die ("Database not found!");

  $btn = $_REQUEST['btn'];
 $btn = !$btn;

 $con->query("INSERT INTO logs (`bool`) VALUES ($btn)");
 $result1 = $con->query("SELECT * FROM logs ORDER by id DESC");
    ?>

索引.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Broahah</title>
    <script src="http://code.jquery.com/jquery-1.9.0.js"></script>

    <script>
  function submitbtn() {

   form1.btn = true;
   var btn = form1.btn.value;
   var xmlhttp = new XMLHttpsRequest();

   xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200)
    {
     var logs = document.getElementById("logs");
     logs.innerHTML = xmlhttp.responseText;
    }
   }

   xmlhttp.open('GET', 'insert.php?btn='+btn, true);
   xmlhttp.send();
  }

  $(document).ready(function(e) {
    $.ajaxSetup({cache:false});
    setInterval(function() {$('#logs').load('logs.php');}, 200);
  });
 </script>

</head>
<body>

  <div id="logs">
   loading...
  </div>
</body>
</html>

感谢您的时间

标签: phpmysqlajaxbuttonboolean

解决方案


推荐阅读