0

I am very new to the coding and writing script to insert data from a form. I'd like to check the validations if those are true then data should be submitted to database. The problem is that when the page is loaded, the data has been submitted to the database without click on submit button.

Here is my code:

  <?php

  include 'config.php';

  ?>

  <html>

  <head> <h1 align="center">Credit form </h1>

   <script> 
     function GoToValidation() {
         var x = document.forms["insert_form"]["name"].value;
         var y = document.forms["insert_form"]["amount"].value;
         if (x == null || x == "") {
             alert("Name field must be filled out");
             return false;
         }

         if (y == null || y == "") {
             alert("Amount field must be filled out");
             return false;
         }
     }
  </script>


  </head>


  <body bgcolor="#D3D3D3">

      <table>

          <form name="insert_form" action="insert.php" method="post" onsubmit="GoToValidation() ">

              <br>
              <br>
              <br>
              <br>

              <table align="center" width="30%" border="1" cellpadding="4" cellspacing="0" bordercolor="#ffffff">

                  <tr>
                      <td>Name</td>
                      <td>
                          <input type="text" name="name">
                      </td>
                  </tr>

                  <tr>
                      <td>Date</td>
                      <td>
                          <input type="text" name="TodayDate">
                      </td>
                  </tr>

                  <tr>
                      <td>Amount</td>
                      <td>
                          <input type="text" name="amount">
                      </td>
                  </tr>

                  <tr>
                      <td></td>
                      <td align="right">
                          <input type="submit" value="submit">
                      </td>
                  </tr>

          </form>



  <?php

    $qinsert = "INSERT INTO finance (name,date,amt,status) 
    VALUES('$_POST[name]','$_POST[TodayDate]','$_POST[amount]','P')";

    if (!mysqli_query($con, $qinsert)) {

        die('Error: ' . mysqli_error($con));

    }

  ?>

  <script>alert ("1 record added") </script>

  <?php
  mysqli_close($con);

  ?>


  </body>

  </html>
halfer
  • 19,824
  • 17
  • 99
  • 186
SriniG
  • 15
  • 1
  • 1
  • 5
  • 4
    **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 Feb 24 '14 at 13:15
  • Don't trust user input! – Nick R Feb 24 '14 at 13:19

5 Answers5

1

The problem is that your PHP script that executes the INSERT query is being executed right when you load the page, as there is nothing stopping it.

I think the easiest solution, also to help you learn the difference between client-side and server-side, is to create a separate page for your PHP. Then call this page on the <form action="PHP_PAGE" property. Then you'll see that the INSERT is only executed on form submit.

halfer
  • 19,824
  • 17
  • 99
  • 186
LcSalazar
  • 16,524
  • 3
  • 37
  • 69
  • Thank you for all your inputs, Even though use the condition if (isset($_POST['submit'])) ot if ($_POST['submit']) { insert code } when the page loaded first time a record has been save to DB. and also as suggested made a separate file for php a record has been submitted here is the code – SriniG Feb 24 '14 at 18:02
  • Can i have a response plz – SriniG Feb 25 '14 at 10:36
1

You're mixing up some things. Remember you're doing client side (browser) validation with your JavaScript code and server side processing with your PHP code.

It's best practice to separate the processing part in kind of "controller file" which does the database stuff and then redirects to or includes a result rendering file. Even better: Try to get familiar with some MVC pattern basics to get a better understanding how and why this is essential for minimal separation of concerns.

Anyway, to solve this problem using your single file approach, you need at least to check if your HTML form was successfully validated and submitted. This can be for example achieved by checking on the submit buttons value transferred with a successful POST request:

if ($_POST[ "submit" ]) {
    // Your database insert statement
}

Be aware (again) that the line <script>alert ("1 record added") </script> is currently processed every time you call that page. Either you generate a status message on the server site and include it in your HTML rendering or you put your JavaScript statement within a PHP if-statement to generate JavaScript code conditionally (which isn't good practice at all!):

if (mysqli_query($con, $qinsert)) {
    echo '<script>alert ("1 record added")</script'; // Better don't do that!
}

While this will probably work, you probably won't get happy with it in the long run. Again, please try to get familiar with some common design patterns. Get an idea of MVC patterns and frameworks for PHP as well as the transforming role of JavaScript these days and how it is best used on client side. Stuff like that one you posted is so very "nineties".

matthias
  • 2,255
  • 1
  • 23
  • 28
0

just check one condition before insert query that if $_post('submit'){your insert code..}

alert ("1 record added")
dev4092
  • 2,820
  • 1
  • 16
  • 15
0

put <form onsubmit="return GoToValidation();"> in your form tag...

Nishant Solanki
  • 2,119
  • 3
  • 19
  • 32
0

You can also use the HTML5 Required function in your input. You won't need the validation script anymore since you will get a notice from the required function.

<tr><td>Name</td> <td><input type="text" name="name" required="required"></td></tr>  

<tr><td>Date </td> <td><input type="text" name="TodayDate"></td></tr>

<tr><td>Amount</td> <td> <input type="text" name="amount" required="required"></td></tr>
Daanvn
  • 1,254
  • 6
  • 27
  • 42
  • @user3346540 Great! If this is your solution would you mind accepting my answer?^^ – Daanvn Feb 25 '14 at 08:07
  • I removed the validation part and put the required thing.even when I load the page first time a record has been adding to DB with click on submit button even after set the conditional check i.e if (isset($_POST['submit'])) ot if ($_POST['submit']) – SriniG Feb 25 '14 at 19:28