Rorrim Rorrim - 1 year ago 82
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>




$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);
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">

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'");
$upAvail = mysqli_query($connect,"UPDATE test SET availability='1' WHERE id='1'");




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 Source

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'];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download