problem inserting data into mysql database from a form...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vikas1111
    New Member
    • Feb 2008
    • 122

    problem inserting data into mysql database from a form...

    Hi All..

    While putting data into database from form if i refresh the php form a blank data will be added into database ... How can i remove that bug???

    Here is my code....
    Code:
    <?php
    $con = mysql_connect("localhost","root","rootwdp");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    mysql_select_db("sample", $con);
    $sql="INSERT INTO usttable (usr_login,usr_password,usr_name,usr_email)
    VALUE ('$_POST[fname]','$_POST[password]','$_POST[fname]','$_POST[email]')";
    if (!mysql_query($sql,$con))
      {
      die('Error: ' . mysql_error());
      }
    mysql_close($con)
    ?>
  • hsriat
    Recognized Expert Top Contributor
    • Jan 2008
    • 1653

    #2
    Apply validations before you insert the data to the database.
    [code=php]
    <?php

    //redirect to the form page if not submitted
    if (!isset($_POST['submit']))
    header ("Location:logi n_form.php");//which ever page is submitting to this script.

    //if any of the parameter is missing.
    if (!isset($_POST[fname]) || !isset($_POST[email]) || !isset($_POST[password]))
    die ("Invalid parameters");


    //---- your code ---
    $con = mysql_connect(" localhost","roo t","rootwdp" );
    if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }
    mysql_select_db ("sample", $con);
    $sql="INSERT INTO usttable (usr_login,usr_ password,usr_na me,usr_email)
    VALUE ('$_POST[fname]','$_POST[password]','$_POST[fname]','$_POST[email]')";
    if (!mysql_query($ sql,$con))
    {
    die('Error: ' . mysql_error());
    }
    mysql_close($co n)
    ?>
    [/code]
    And make sure you add name="submit" to the submit button.

    I would suggest you to do the same validations in PHP before you insert data, which you do in JavaScript onsubmit of form (if you are doing any).

    Comment

    • jessica87
      New Member
      • May 2008
      • 10

      #3
      thanks for the tips...
      i have the same problem to.....
      ^_^

      Comment

      • vikas1111
        New Member
        • Feb 2008
        • 122

        #4
        hi hsriat

        thanks its working........

        Comment

        • hsriat
          Recognized Expert Top Contributor
          • Jan 2008
          • 1653

          #5
          You are welcome... :)

          I'm glad that one reply helped both of you.

          Comment

          Working...