Mysql表格单元格在点击

时间:2016-05-18 01:12:30

标签: php mysql

我正在尝试编写一个改变某个公寓可用性的PHP代码。这是我的代码:

<!DOCTYPE html>
<html>

    <head>
        <title></title>
    </head>

    <body>

        <?php 

            $servername = "localhost";
            $username = "bla";
            $password = "blabla";
            $dbname = "testDB";

            // Create connection
            $connect = mysqli_connect($servername, $username, $password, $dbname);

            // Check connection
            if ($connect->connect_error) {
                die("Connection failed: " . $connect->connect_error);
            }else{
                echo "Connected successfully to the database: " . $dbname . "<br><br>";
            }

            $query = "SELECT * FROM test";
            $result = mysqli_query($connect, $query);
            $row = mysqli_fetch_array($result);

            echo "id: " . $row["id"] . " // Address: " . $row["address"] . " // Rooms: " . $row["rooms"] . " // Availability: " . $row["availability"] . ".<br>";
            ?>
                <form method ="post" action ="<?php $_PHP_SELF ?>">
                    <input name="update" type="submit" value="Change Availability">
                </form>
            <?php

            if(isset($_POST["update"])) {
                $avail =  mysqli_query($connect,"SELECT availability FROM test WHERE id='1'");
                $availCheck = mysqli_fetch_array($avail);
                settype($availCheck, "int");

                if($availCheck == 1){
                    $upAvail = mysqli_query($connect,"UPDATE test SET availability='0' WHERE id='1'");
                }else{
                    $upAvail = mysqli_query($connect,"UPDATE test SET availability='1' WHERE id='1'");
                }
            }

        ?>

    </body>

</html>

这是我得到的输出:

成功连接到数据库:testDB

id:1 //地址:3787 cote des neiges //房间:2 //可用性:1。 更改可用性

所以这是我的问题。当可用性为1并按下按钮时,它会变为0.但在此之后,当我再次按下按钮时,它不会变回1.

为什么?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您没有切换availabilitymysqli_fetch_arraytest表中获取与id匹配的行(id = 1)。因此,在将非空数组转换为整数后,$availCheck将始终等于1

您可以使用单个MySQL查询替换所有逻辑以切换值。

UPDATE test SET availability = IF(availability = 1, 0, 1) WHERE id=1

我想你想做什么:

 $availCheck = mysqli_fetch_array($avail)['availability'];