Connecting Tech Pros Worldwide Forums | Help | Site Map

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

vikas1111's Avatar
Member
 
Join Date: Feb 2008
Location: 12° 18' N, 76° 42' E
Posts: 118
#1: May 24 '08
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....
Expand|Select|Wrap|Line Numbers
  1.  
  2. <?php
  3. $con = mysql_connect("localhost","root","rootwdp");
  4. if (!$con)
  5.   {
  6.   die('Could not connect: ' . mysql_error());
  7.   }
  8. mysql_select_db("sample", $con);
  9. $sql="INSERT INTO usttable (usr_login,usr_password,usr_name,usr_email)
  10. VALUE ('$_POST[fname]','$_POST[password]','$_POST[fname]','$_POST[email]')";
  11. if (!mysql_query($sql,$con))
  12.   {
  13.   die('Error: ' . mysql_error());
  14.   }
  15. mysql_close($con)
  16. ?>
  17.  

hsriat's Avatar
Expert
 
Join Date: Jan 2008
Location: Bath, UK
Posts: 1,609
#2: May 24 '08

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


Apply validations before you insert the data to the database.
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. //redirect to the form page if not submitted
  4. if (!isset($_POST['submit']))
  5. header ("Location:login_form.php");//which ever page is submitting to this script.
  6.  
  7. //if any of the parameter is missing.
  8. if (!isset($_POST[fname]) || !isset($_POST[email]) || !isset($_POST[password]))
  9. die ("Invalid parameters");
  10.  
  11.  
  12. //---- your code ---
  13. $con = mysql_connect("localhost","root","rootwdp");
  14. if (!$con)
  15.   {
  16.   die('Could not connect: ' . mysql_error());
  17.   }
  18. mysql_select_db("sample", $con);
  19. $sql="INSERT INTO usttable (usr_login,usr_password,usr_name,usr_email)
  20. VALUE ('$_POST[fname]','$_POST[password]','$_POST[fname]','$_POST[email]')";
  21. if (!mysql_query($sql,$con))
  22.   {
  23.   die('Error: ' . mysql_error());
  24.   }
  25. mysql_close($con)
  26. ?>
  27.  
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).
Newbie
 
Join Date: May 2008
Location: malaysia
Posts: 10
#3: May 25 '08

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


thanks for the tips...
i have the same problem to.....
^_^
vikas1111's Avatar
Member
 
Join Date: Feb 2008
Location: 12° 18' N, 76° 42' E
Posts: 118
#4: May 29 '08

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


hi hsriat

thanks its working........
hsriat's Avatar
Expert
 
Join Date: Jan 2008
Location: Bath, UK
Posts: 1,609
#5: May 29 '08

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


You are welcome... :)

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