Rorrim Rorrim - 6 months ago 23
PHP Question

Mysql table cell doesn't change value on click

I am trying to write a php code that changes the availability of a certain apartment. Here is my code:

<!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>


And this is the output I get:

Connected successfully to the database: testDB

id: 1 // Address: 3787 cote des neiges // Rooms: 2 // Availability: 1.
Change Availability

So here is my issue. When the availability is 1 and I press the button it changes to 0. But after that, when I press the button again, it doesn't change back to 1.

Why is that?

Thank you for the help.

Answer

You're not toggling the availability. The mysqli_fetch_array fetches the row from the test table matching the id (id=1). As a result, $availCheck will always equal 1 after you cast the non-empty array to an integer.

You can replace all that logic with a single MySQL query to toggle the value.

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

I think what you wanted to do:

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