0
<?php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test_db";


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

//check radio button and update sql accordingly

if (isset($_GET['calc'])) {

$calc = $_GET['calc'];
}

if ($calc='average'){
$sql1 = "UPDATE `config` SET `calc_category`=1 WHERE 1";
$conn->query($sql1);
} elseif ($calc='high'){
$sql1 = "UPDATE `config` SET `calc_category`=2 WHERE 1";
$conn->query($sql1);
} else {
$sql1 = "UPDATE `config` SET `calc_category`=3 WHERE 1";
$conn->query($sql1);
}


?>

In the above code even if the $calc is equal to 'high' or something other than 'average', it still updates the database with 'calc_category'=1 which is only supposed to happen when first 'if' condition is true.

I have echoed the value of $calc and it changes based on which radio button is selected but I am not sure why always first 'if' condition code is getting executed.

I am new to PHP,SQL please help me where am I going wrong.

Pie
  • 11
  • 3
  • in the query where 1 means all rows will be updated.. check where clause and also use `==` (equal operator) instead of `=` (assignment operator) – Bilal Ahmed Aug 11 '18 at 06:14
  • 1
    `$calc='average'` is an assignment, not a test for equal to. `$calc=='average'` – Nigel Ren Aug 11 '18 at 06:15

3 Answers3

2

double equal to needed...

 if ($calc=='average'){ /****// == instead of = //*****/
     $sql1 = "UPDATE `config` SET `calc_category`=1 WHERE 1";
     $conn->query($sql1);
 } elseif ($calc=='high'){ /****// == instead of = //***/
     $sql1 = "UPDATE `config` SET `calc_category`=2 WHERE 1";
     $conn->query($sql1);
 } else {
     $sql1 = "UPDATE `config` SET `calc_category`=3 WHERE 1";
     $conn->query($sql1);
 }

also check your query near Where clause.... it is where 1 ?????

1

In your elseif statement you are setting $calc = 'high'. That is not a comparison. In order for you to evaluate if the terms are equal you need to use == or === depending on how strict you need the comparison to be.

if ($calc == 'average'){
$sql1 = "UPDATE `config` SET `calc_category`=1 WHERE 1";
$conn->query($sql1);
} elseif ($calc == 'high'){
$sql1 = "UPDATE `config` SET `calc_category`=2 WHERE 1";
$conn->query($sql1);
} else {
$sql1 = "UPDATE `config` SET `calc_category`=3 WHERE 1";
$conn->query($sql1);
}
Joseph_J
  • 3,654
  • 2
  • 13
  • 22
0

for Comparison two values you must use '==' instead of '='. appending value to a variable return true value so elseif section not work. i hope it be useful.

false usage : if ($calc='average') true useage : if ($calc == 'average')