-2

I am trying to write a PHP file to update data in my database, but for some reason the if statements are not working. I have tested to see if all posts are filled and everything should be working. Please help.

<?php
session_start();
include 'dbh.php';

$newname = htmlspecialchars($_POST['nieuwenaam']);
$newprice = htmlspecialchars($_POST['nieuweprijs']);
$oldname = $_POST['oudenaam'];
$oldprice = $_POST['oudeprijs'];
$pid = $_POST['pid'];

if(!isset($newname) && !isset($newprice))
   {
      echo 'hoi';
   }
elseif(!isset($newname) && isset($newprice))
   {
        echo $newprice;
        $sql = "UPDATE producten SET naam = '$oldname' , price = '$newprice' WHERE product_id = $pid";
        $query = $PDO->prepare($sql);   
        $query->execute();
    }
elseif(isset($newname) && !isset($newprice))
    {
        echo $newname;
        $sql = "UPDATE producten SET naam = '$newname' , price = '$oldprice' WHERE product_id = $pid";
        $query = $PDO->prepare($sql);   
        $query->execute();
    }
J. Murray
  • 1,460
  • 11
  • 19
GewoonRik
  • 1
  • 1
  • "not working" ... what are you expecting to happen and what is actually happening? – lagbox Sep 18 '20 at 13:13
  • All of your condition in `if` and `elseif` are false so it never execute your querys. You defined `$newname` and `$newprice` at the top of your script so all of your `isset()` will return true – catcon Sep 18 '20 at 13:14
  • `$newname = htmlspecialchars(` always sets `$newname` (could be empty, but it **is** set. So testting for `isset($newname)` has no use, it's always true. – Michel Sep 18 '20 at 13:17
  • And why using prepared statements if you put the variables straight in the query. Take a look [here](https://stackoverflow.com/a/6379483/1685196) for proper use of prepared statements. – Michel Sep 18 '20 at 13:25

2 Answers2

0

well you are kinda setting your variables above your condition and then your checks says if the variables are set or not . I am guessing your variables are alllways set and that is why it is seemingy not working.

Instead of isset($newname) use isset($_POST["nieuwenaam"]). It may work.

double-beep
  • 5,031
  • 17
  • 33
  • 41
-1

Replace !isset() by empty() and isset() by !empty()

if(empty($newname) && empty($newprice)){
  echo 'hoi';
}elseif(empty($newname) && !empty($newprice)){
    echo $newprice;
    $sql = "UPDATE producten SET naam = '$oldname' , price = '$newprice' WHERE product_id = $pid";
    $query = $PDO->prepare($sql);   
    $query->execute();
}
elseif(!empty($newname) && empty($newprice)){
    echo $newname;
    $sql = "UPDATE producten SET naam = '$newname' , price = '$oldprice' WHERE product_id = $pid";
    $query = $PDO->prepare($sql);   
    $query->execute();
}