Hi All Can someone please point out to me what is wrong with this code? Each time I refresh the page it inserts duplicate data in database. Other than that it doesn't give out any errors. Some help will be greatly appreciated. <? include("config.php"); function insert(){ $id = $_POST['id']; $news = $_POST['news']; if(empty($news)) error_message("You need to enter some text in news box!"); $query = "INSERT INTO news VALUES (NULL,'$news')"; $result = mysql_query($query)or die(mysql_error()); if (@mysql_query($query)) { echo '<p>Your Fresh news have been added. </p>'; } else { echo '<p>Error adding submitted Information: ' . mysql_error() . '</p>'; } } function form(){ ?> <center><h1>Add News</h1> <form name="action" id="action" method="post" action="<?=$_SERVER['PHP_SELF']?>"> <table width="60%" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="18%"></td> <td width="82%"><input name="f_id" type="hidden" value="" /></td> </tr> <tr> <td></td> <td>Add fresh news here and click 'Submit' button</td> </tr> <tr> <td> </td> <td><textarea name="news" cols="55" rows="15"> </textarea></td> </tr> <tr> <td> </td> <td><input name="submit" type="submit" value="Submit" /> <input name="reset" type="reset" value="Reset" /></td> </tr> </table> </form></center> <? } if (! isset($_POST['submit'])){ form(); }else{ insert(); } Code (markup): Thanks Zed
This is because the submitted form data is still there after being submitted. To avoid this, simply refresh the page ( using php or javascript) After this line : echo '<p>Your Fresh news have been added. </p>'; add this: if ( mysql_affected_rows() == 1) { // 1 row has been inserted // redirect the user to another page / to the same page ( to clear submitted data ) header('location : where_u_want_user_to_go_after_submitted.php'); } PHP: You can do the same using javascript ( put after echo '<p>Your Fresh news have been added. </p>'; ) <script type="text/javascript"> window.location = window.location </script> HTML: ================== If you want to display a 'successful' message after the redirect, you can use this: if ( mysql_affected_rows() == 1) { // 1 row has been inserted // redirect the user to another page / to the same page ( to clear submitted data ) header('location : where_u_want_user_to_go_after_submitted.php&success'); } PHP: Then use this at the place you want the success message to be shown if ( isset($_GET['success']) ) { print 'Success! '; } PHP:
Or try using mysql_insert_id(), b.t.w you need to check your input (validate it) and use mysql_real_escape_string to gain more security!