1

When i first enter my form it calls my php function and displays the error for entering a blank. How do i stop that and only call the function when i submit and not on page load? I feel like i need to do a "if(isset" somewhere but i can't figure it out.

    <head>
    <html>
    <center>
    <body onLoad="document.chip_insert.chip_number.focus()";>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script type="text/javascript">

    function validateName(){
        var x=document.forms["chip_insert"]["order_number"].value;
        if (x.length<=10) {
            document.forms["chip_insert"]["order_number"].focus();
            document.getElementById("order_number").style.border='3px solid red';
            document.getElementById("erron").innerHTML = "Invalid";
            return false
        }
        if (x.length=11) {
            document.getElementById("order_number").style.border='1px solid black';
            document.getElementById("erron").innerHTML = "";
        }
        if (x==null || x=="")
        {
          document.forms["chip_insert"]["order_number"].focus();
          document.getElementById("order_number").style.border='3px solid red';
          document.getElementById("erron").innerHTML = "Invalid";
          return false;
        }
    }
    function validateForm(){
        var y=document.forms["chip_insert"]["chip_number"].value;
        if (y.length<=14) {
            document.forms["chip_insert"]["chip_number"].focus();
            document.getElementById("chip_number").style.border='3px solid red';
            document.getElementById("errcn").innerHTML = "Invalid";
            return false
        }
        if (y==null || y=="")
        {
          document.forms["chip_insert"]["chip_number"].focus();
          document.getElementById("chip_number").style.border='3px solid red';
          document.getElementById("errcn").innerHTML = "Invalid";
          return false;
        }
    }
    function isNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
    }
    function isaNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
    }
    window.addEventListener('keydown', keydownCallback);

    function tabOnEnter(field, event) {
        if (event.keyCode === 13) {  
            if (event.preventDefault) {
                event.preventDefault();
            } else if (event.stopPropagation) {
                event.stopPropagation();
            } else {
                event.returnValue = false;
            }
            getNextElement(field).focus();
            return false;
        } else {
            return true;
        }
    }

    function getNextElement(field) {
        var form = field.form;
        for ( var e = 0; e < form.elements.length; e++) {
            if (field == form.elements[e]) {
                break;
            }
        }
        return form.elements[++e % form.elements.length];
    }

    function keydownCallback(event) {
      if (event.keyCode === 191) {
        setTimeout(setFocusToTextBox);
      }
    }


    function setFocusToTextBox() {
      document.getElementById("order_number").focus();
      document.forms["chip_insert"]["order_number"].value="";
      document.forms["chip_insert"]["chip_number"].value="";
       if (event.preventDefault) {
                event.preventDefault();
            } else if (event.stopPropagation) {  
                event.stopPropagation();
            } else {
                event.returnValue = false;
            }
    }
    </script>
    </center>
    <center>
    <div
    style="width:1000px;
    height:300px;
    border:6px ridge
    blue;">
    <?php
    $value = "";
    if( isset( $_POST ["order_number"] )) $value = $_POST ["order_number"];
    ?>

    </script>
    <style>
    h1 { 
        font-size: 22pt;
        font-family: verdana;
    }
    </style>
    <h1>Jeffers HomeAgain Microchip Entry</h1>
    <style>
    body {
        background-image: url("http://JVSIntranet/microchip/image.jpg");
    }
    </style>

    <form name="chip_insert"  id="chip_insert" action="<?php echo $PHP_SELF;?>" onsubmit="return validateForm()" method="post" onkeydown="keydownCallback(event)">
    <label style="font-size:18pt; color:blue; font-family:verdana;" for="order_number">Order Number</label><br>
    <input tabindex="1" style="height:40px;font-size:16pt; font-family:verdana;" maxlength="11" type="text" name="order_number" onblur="validateName(order_number)"  id="order_number"  value="<?php echo $value; ?>" onkeypress="return isNumber(event)"  required="required" onkeydown="return tabOnEnter(this, event)" onfocus="this.focus();this.select()" /><span id="erron"></span> <br /><br />
    <label style="font-size:18pt; color:blue; font-family:verdana;" for="chip_number">Chip Number</label><br>
    <input tabindex="2" style="height:40px;font-size:16pt; font-family:verdana;" maxlength="15" type="text" name="chip_number" id="chip_number" required="required" onkeydown="validateName()" onfocus="this.focus();this.select()" onkeypress="return isaNumber(event)" /><span id="errcn"></span> <br /><br />
    <input tabindex="7" type="submit" value="Enter" />
    </form>
    </center>

    <center>
    <style>
    font { color: red; font-size: 25pt; font-family: verdana; }
    </style>

    <font>

        <?php
        $servername = "servername";
        $username = "username";
        $password = "password";
        $dbname = "dbname"
        // Create connection
        $conn = mysqli_connect($servername, $username, $password, $dbname);
        // Check connection
        if (!$conn) {
            die("Connection failed: " . mysqli_connect_error());
        }   
        $sql = "INSERT INTO MICROCHIP_TBL (chip_number,order_number)
        VALUES 
        ('$_POST[chip_number]','$_POST[order_number]')";

         if (!mysqli_query($conn, $sql)) { 
            echo "ERROR: NUMBER IS ALREADY IN DATABASE! SCAN YOUR CHIP NUMBER AGAIN!";
        }
        mysqli_close($conn);
        ?>
</center>
</font>
<center>
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sqli = "SELECT * FROM MICROCHIP_TBL ORDER BY entry_date desc LIMIT 20";
$result = $conn->query($sqli);

if ($result->num_rows > 5) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo " " . $row["entry_date"] . "::You scanned Order Number--" . $row["order_number"] . "--with Chip Number--" . $row["chip_number"]. "<br>";
        }
    }else{
        echo "0 results";
    }
$conn->close();
?>
</center>
</div>
</body>
</head>
</html>
chris bahr
  • 155
  • 3
  • 15
  • 2
    **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Jan 27 '15 at 16:26
  • Not only SQL injection but also HTML injection. @Chris bahr you really should make checks for both types of possible attacks else you are leaving that webpage wide open. – Thomas Jan 27 '15 at 17:01
  • Its just an internal terminal for us to put our Microchips into a database instead of writing them down. – chris bahr Jan 27 '15 at 17:11

2 Answers2

4

You can do:

if (isset($_POST['submit'])) {
   // code to execute on submit
} else {
   // code to execute on first request
}

// code to always execute

That's assuming that 'submit' is the name of your submit button, and the form method is post.

  • form method is post and submit button is "submit" but when i try your suggestion the page won't submit anything. Just reloads with no post to database – chris bahr Jan 27 '15 at 16:37
  • 1
    @chrisbahr perhaps you could edit your post to include the full code? Also, there might be something else go wrong. Why not start with a test script that outputs something in the if-branch, so that you know for sure that that is working? –  Jan 27 '15 at 16:39
  • 1
    I didn't want to put the whole code because i'll probably get more opinions then my answer and i didnt't want to add more to the fire. Anyways there's my full code up top. Note: the problem that i'm having still did it when it was just a simple post form and 1 javascript function. All the extras couldn't be the cause. – chris bahr Jan 27 '15 at 16:54
  • @chrisbahr did you add the name 'submit' to your submit field? Then it should work, it does here at least. –  Jan 27 '15 at 18:01
  • type="submit" and value="enter" is what i have. I've tried it with enter and submit – chris bahr Jan 27 '15 at 18:20
  • @chrisbahr Could you try adding name="submit"? That's what I meant with my answer. –  Jan 27 '15 at 18:32
  • Awesome man! i honestly was about to give up for today. Works fine after i took the value="enter" out and put name="submit". Still defaults name to submit query but i'm ok with that. – chris bahr Jan 27 '15 at 18:39
0

One method I see there is to put a hidden field into the form for example:

<input type="hidden" name="IsSubmitted" id="IsSubmitted" value="1" />   

Then in your code you check:

if (isset($_POST["IsSubmitted"]) && $_POST["IsSubmitted"] != "")
{
  // Do you stuff
}
Thomas
  • 2,886
  • 3
  • 34
  • 78
  • well i tried it around the post function and it stops the form from submitting all together. if i do it around the whole thing or just the connect then it wont connect to the server at all obviously. Assuming i tried it in all the possible places, it didn't work. – chris bahr Jan 27 '15 at 17:09
  • That id should be a name to send it correctly. Also, if you want to hide an input, just use type="hidden". Furthermore, you only need to test on isset($_POST['IsSubmitted']), the other conditions are redundant. –  Jan 27 '15 at 18:34