0

Here's my code, for some reason, whether I specify a value for the input id or not, it seems to provide one, because ONLY the if statement is run. Also, when I provide a value for the id (or not), nothing is updated or changed.

<?php
$culture = $_POST["culture"];
if (isset($_POST["id"])) {
    $UID = $_POST["id"];
    mysql_query("UPDATE culture SET cult_desc='$culture' WHERE cult_id=$UID");
    echo $UID . "  " . $culture . " If Statement Activated";
}
else {
     mysql_query("INSERT INTO culture
             VALUES(cult_desc='$culture')");
             echo $culture . " Else Statement Activated";
}
?>

Here's the html code:

    <form action="addculture.php" method="POST">
          <span><input type="text" size="3" name="id" />
          <input type="text" name="culture" />
        <input type="submit" value="add" /></span>
    </form>
Ryan Schafer
  • 245
  • 2
  • 9
  • 16

2 Answers2

5

If your ID value comes from an <input> field in the browser, then isset($_POST['fieldname']) will ALWAYS be true. An input field is always submitted the server, even if there is no data in it.

If you want to check if there's something in the field, then do this:

if (isset($_POST['id']) && ($_POST['id'] !== '')) {
   ...
}

That'll check if the id field actuall exists (which is should), and if it contains something OTHER than an empty string - all data coming out of $_POST/$_GET is a string, even if it's numeric data.

Marc B
  • 356,200
  • 43
  • 426
  • 500
0

Try this if-statement instead:

if (isset($_POST["id"]) && trim($_POST["id"]) != "") {

If you post the data from a form and you have an input for id, I believe the id POST-variable will be set but empty.

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103