Search code examples
phpsql-updatetogglehref

PHP href update or toggle true 1 or false 0 value in sql


I have a list of products output from a database, I'd like to have an option for a product to be a "favourite" product and show a coloured icon when the value is '1' for favourite or show grey when '0' for not being a favourite.

My questions is how to change/toggle/update the variable to '0' if it is currently '1' and how to change to '1' of it is currently '0' with the same href.

I can display the above correctly with the following...

$favourite = $row["favourite"];

switch(strtoupper($favourite))
{
case '0': $favourite_img = 'heart_16-no'; break;
case '1': $favourite_img = 'heart_16'; break;
default: $favourite_img = 'heart_16-no'; break;
}

$fav_img = "<img src='https://www.mysite.com/storeadmin/img/Basic_set_Png/$favourite_img.png'>";

I have the product value in the database updated via a href to '1' with the following just not back to '0' when necessary...

//make item favourite
if(isset($_GET['favouriteid'])){
$id_to_favourite = $_GET['favouriteid'];
$sql = mysql_query("UPDATE products SET favourite=1 WHERE id='$id_to_favourite' LIMIT 1") or die (mysql_error());
header("location: inventory_list.php");
exit();
}

I'm sure this is easy I just don't know the correct way to go about it so can really search for any reference.

Something like this perhaps...

if(isset($_GET['favouriteid'])){
  $id_to_favourite = $_GET['favouriteid'];
  if (isset($row["favourite"]) && $row['favourite'] == '0') {
  mysql_query("UPDATE products SET favourite=1 WHERE id='$id_to_favourite' LIMIT 1") or die (mysql_error());
    } else if (isset($row["favourite"]) && $row['favourite'] == '1') {
    mysql_query("UPDATE products SET favourite=0 WHERE id='$id_to_favourite' LIMIT 1") or die (mysql_error());
    }
    header("location: inventory_list.php");
    exit();
    }

Solution

  • Since it's a boolean, you can use bang (!) to reverse or toggle it

    e.g.,

    UPDATE products SET favourite = !favourite WHERE id='$id_to_favourite' LIMIT 1
    

    This will simply change 0 to 1, or 1 to 0