Duplicate records

Hi,

Please correct my code so as to insert one record to doc table, right now as and page is refreshed same record gets added, in other words we need to block creating new records as and when page getting refreshed, also it should insert records to doc table as and when user clicks submit button,

Thanks
 <?php
SESSION_start();

			  if(!isset($_SESSION['email']))
			    {
				
                echo"access denied";
				exit;
				}
				else{
			    $email=$_SESSION['email'];
			   include("menu.php");
			    $num=$_SESSION['num'];
			    $date=date("Y/m/d");
			
				}
							
				
?>



<html>
           <head>
           </head>
  
  
            <body>
			 <div style="position:absolute; top:143px; left:292px; width:999px; height:244px; background-color:pink; border-radius:15px;">
			 <table>
            <form  enctype="multipart/form-data"  action=""  method= "POST">
			
			<tr><td>Document Type:</td><td><select name="doc_type" >
			         <option value="police report" selected="true">Police report file</option>
					 <option value="medical report">Medical report file</option>
					 <option value="purchase bills">Purchase invoice report</option>
					 <option value="survey report">Survey report file</option>
			</select></td></tr>
              <tr><td>Settlement Number:</td><td><input type="text" name="cnum" value="<?php echo $num;?>"  readonly /><br /></td></tr>
              <tr><td>Created Date :</td><td><input type="text" name="doc_cdate" value=""  /></td></tr>
	          <tr><td>Created By :</td><td><input type="text" name="doc_cby"  value=" <?php echo $email; ?> " /></td></tr>
			  <tr><td>Description :</td><td><input type="text" name="doc_comment"  value=" " /></td></tr>
			  <input type="hidden" name="max_file_size" value="124111111"/>
                <tr><td>Pick your document ?</td><td><input type="file" size="2022222" name="thefile" /></td></tr>
	           <tr><td></td><td><input type="submit" name="submit" value=" Uplaod this!"></input></td></tr>
			   
			   
                </form>
  </div>
             </body>
              </html>
<?php
			  
					
mysql_connect("localhost","root","");
mysql_select_db("shri");	

    $sql="select * from doc where cnum='$num'";
    $result=mysql_query($sql);
    $count=mysql_affected_rows();
	
	if($count>0)
	{
	
		 echo"<table style=\"  border: 1px solid black; background-color:pink; width:999px; cellborder:1; position:relative; top:53px;border-radius:22px; \">";
		echo"<tr><td><h3>Document View</h3></td></tr>";
	echo"<tr><td style=\"  border: 1px solid black;\">Settlement No</td><td style=\"  border: 1px solid black;\">Document Type</td><td style=\"  border: 1px solid black;\">Created date</td><td style=\"  border: 1px solid black;\">Created by</td><td style=\"  border: 1px solid black;\">Comment</td><td style=\"  border: 1px solid black;\">Veiw</td></tr>";
	  while($row=mysql_fetch_array($result))
		        { $cnum=$row['cnum'];
			      $doc_type=$row['doc_type'];
			      $doc_cdate=$row['doc_cdate'];
			      $doc_cby=$row['doc_cby'];
			      $path=$row['path'];
				  $doc_comment=$row['doc_comment'];
			      
		echo"<tr><td style=\"  border: 1px solid black;\">$cnum</td><td style=\"  border: 1px solid black;\">$doc_type</td><td style=\"  border: 1px solid black;\">$doc_cdate</td><td style=\"  border: 1px solid black;\">$doc_cby</td><td style=\"  border: 1px solid black;\">$doc_comment</td><td style=\"border: 1px solid black;\" ><a href=\"$path\" style=\"color:red;\">Click here</a></td></tr> ";
		}echo"</div>";
		echo"</table>";
			   
	
	}
	else
	{echo"<table style=\" border:1 solid gray ; background-color:pink ; width:999px; cellborder:1; position:relative; top:63px; \">";
	  echo"<tr><td>Settlement No</td><td>Document Type</td><td>Created date</td><td>Created by</td><td>View</td></tr>";
	     echo"<tr><td colspan=\"5\"><center/>No rows returned</td></tr>";
		 echo"</div>";
		 echo"</table>";
	
	
	}
  
  
  

  


	  
	  if((isset($_POST['submit'])))
	    {    
			 $path="";
                 $doc_type=$_POST['doc_type'];
				$doc_cby=$_POST['doc_cby'];
				$doc_cdate=$_POST['doc_cdate'];
				$cnum=$_POST['cnum'];
				$doc_comment=$_POST['doc_comment'];
       if(!empty($doc_comment))
  		{
			if(($_FILES['thefile']['size']==0)|| (empty($_FILES['thefile']['tmp_name'])))
               {
                echo("<p>You didn't select document </p>\r\n");
               } else if($_FILES['thefile']['size'] > 50001110) 
			            {
                          echo("<p>The file was too large.</p>\r\n");
                       } else if($_FILES['thefile']['error'] !== UPLOAD_ERR_OK) 
					            { 
								
								
								echo("<p>There was an error uploading.</p>\r\n");
                                        } 
     else {
        if(!file_exists('/image_uploaded')) mkdir('image_uploaded');
       

                 if(move_uploaded_file($_FILES['thefile']['tmp_name'],'image_uploaded/'. $_FILES['thefile']['name'])) 
                  { echo("<p>File uploaded successfully!</p>\r\n");
                  $path='image_uploaded/'.$_FILES['thefile']['name'];
			   
                mysql_connect("localhost","root","");

                mysql_select_db("shri");
				$sql=("insert into doc(doc_type,cnum,doc_cdate,doc_cby,path,doc_comment) values('$doc_type','$cnum','$doc_cdate','$doc_cby','$path','$doc_comment')");
				$result=mysql_query($sql);	
				$count= mysql_affected_rows();
				echo $count;
               if(mysql_affected_rows() > 0)
                            {  
		                     echo "Your document has been uploaded !!";
				               exit;
				             }  															   
				 else{  
					  echo "Oye!we missed it ,please submitagain,Thank you"; 
				       exit;
			          }
					  
			   
			   
			      }else {
                          echo("<p>There was an error moving the file.</p>\r\n");
						 }
		 }
				
				 
			} 
													  
}
										  	
															
													   												   
													      
?>

 
			  

Open in new window

shrikanthnkAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
There are so many things wrong with this script I don't know where to begin, so this is not listed in the order of importance, but all of the elements are important at the same time.  If it seems like this is a lot to absorb, don't worry, or hurry.  You have a lot of work ahead of you if you want to bring this script up to any kind of semi-pro standard.

You can mark a column UNIQUE in MySQL and MySQL will throw error 1062 when an attempt is made to INSERT or UPDATE that would cause a duplicate.  This is the surest and easiest way to detect duplication.  Simply trap the error number and test.

You must never use unfiltered external data in a query.  Please learn about the standard data base escape functions and the filter_var() function

All of the SQL query functions and methods return some kind of value.  Your script must test for this and handle errors.  MySQL is not a black box; it can and will fail for reasons that are sometimes outside of your control.  You will need to learn about "errno" and "error" functions.  See below for the article link that will show this.

Dates for internal use should be in ISO-8601 format. This article tells how to handle DATETIME values in PHP and MySQL.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

PHP is doing away with MySQL support, so that will have to change.  This article tells you why that is happening and what you must do to keep your scripts running.  It also shows the correct way to escape the external data for safe use in a query string.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

Coding standards matter and neatness counts.  If you line the code up neatly so that it is easy to read, you will find that your debugging goes much faster.  Almost any coding standard is helpful.  Personally, I use a slightly modified ZEND standard (or whatever my clients require).

PHP suppresses Notice messages by default.  This is a simply terrible practice.  It is an artifact of the 1990's when the whole idea behind PHP was to make it really easy.  Unfortunately when you suppress the notices, you lose critical information about what PHP is doing with your script.  You might want to add error_reporting(E_ALL) to the top of your scripts.  I couldn't work without it!
0
Ray PaseurCommented:
It appears that you posted this comment on one of the EE articles instead of in this question thread, so I copied it and put it here:
---
Hi sir,

This is just to update that code written by me works fine except one particular issue as mentioned earlier.

That is  record will be inserted to the doc table which is as per design. Also one of the column in that table should hold path of the updated document  and it is working fine. later clicking on that link should display  uploaded image/file. Again this particular functionality works fine..

Then what is not working ??

after successful entry to the table and clicking on refresh buttin will insert same record again with different row id,(primary key]. i hope now you have understood my issue as well as concern.  

Actiona taken by me to resolve this issue  
as mentioned earlier  i have put condition whether submit button is clicked or not. if submit button is clicked then insert the rec to table else no.

what is happening right now.

first time record gets inserted without any problem. user can view the document without any issue.But if the user clicks on refresh button ,  same record gets inserted again!!

thanks,
Shrikanth
0
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

shrikanthnkAuthor Commented:
yes...  Sorry for that..
0
Ray PaseurCommented:
No problem, we have it in the right place now :-)

Let me try this one again.

You can mark a column UNIQUE in MySQL and MySQL will throw error 1062 when an attempt is made to INSERT or UPDATE that would cause a duplicate.  This is the surest and easiest way to detect duplication.  Simply trap the error number and test.

It may be necessary to redesign the logic of the script in order to achieve what you want to do.  That's why I posted the links to the other learning resources.

You can also prevent repeated submissions of the same data.  This script is a teaching example showing how to do that.  But these are really two different issues, hence two different technical approaches to the problems.

<?php // RAY_multi_submit.php
error_reporting(E_ALL);


// PREVENT MULTIPLE SUBMISSIONS DUE TO REPEATED REFRESH, CLICKS ON SUBMIT BUTTON, OR FIRING THE BACK BUTTON
// EXAMPLE:
//    if ( multi_submit() )
//    {
//       handle error
//    }
//    else
//    {
//       normal processing
//    }


// ALWAYS START THE PHP SESSION ON EVERY PAGE
session_start();



// A FUNCTION TO RETURN TRUE OR FALSE ABOUT MULTI-SUBMIT CONDITIONS
function multi_submit($type="POST")
{
    // MAKE THE FUNCTION WORK FOR EITHER GET OR POST SUBMITS
    $input_array = (strtoupper($type) == "GET") ? $_GET : $_POST;

    // GATHER THE CONTENTS OF ALL THE SUBMITTED FIELDS AND MAKE A MESSAGE DIGEST
    $string = NULL;
    foreach ($input_array as $val)
    {
        // CONCATENATE ALL SUBMITTED VALUES
        $string .= $val;
    }
    $string = md5($string);

    // IF THE SESSION VARIABLE IS NOT SET THIS IS NOT A MULTI-SUBMIT
    if (!isset($_SESSION["_multi_submit"]))
    {
        // SAVE THE SUBMITTED DATA MESSAGE DIGEST
        $_SESSION['_multi_submit'] = $string;
        return FALSE;
    }

    // IF THE SESSION DATA MATCHES THE MESSAGE DIGEST THIS IS A MULTI-SUBMIT
    if ($_SESSION['_multi_submit'] === $string)
    {
        return TRUE;
    }
    else
    {
        // SAVE THE MESSAGE DIGEST TO DETECT FUTURE MULTI-SUBMIT
        $_SESSION['_multi_submit'] = $string;
        return FALSE;
    }
}



// SHOW HOW THIS IS DONE
if (!empty($_POST))
{
    if (multi_submit())
    {
        die("ALREADY GOT THAT");
    }
}



// CREATE THE FORM FOR THE DEMONSTRATION
$form = <<<FORM
<form method="post">
ENTER SOMETHING, THEN REENTER IT
<input name="foo" />
<input type="submit">
</form>
FORM;

echo $form;

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
shrikanthnkAuthor Commented:
Hi ...

After spending overnight time i could able to resolve this issue with same code without making any major changes. it seems this issue is common in all types of browser. So need to navigate to different page.

So code written by is  correct !!

Thank you all
0
Ray PaseurCommented:
The code is NOT CORRECT if the client can accidentally make duplicate updates.  At a minimum the client must be asked to confirm the second update.  Anything less would get an employed programmer fired, and would probably get a consultant sued!

It may be necessary to redesign the logic of the script in order to achieve what you want to do.  That's why I posted the links to the other learning resources.
0
InsoftserviceCommented:
steps to avoid duplicate
1> add unique constraint to your column
2> after inserting redirect it to other page and display successful message.
i.e before line  echo "Your document has been uploaded !!"; so that even if client press refresh button by mistakenly it will refresh the redirected page.

Hope it helps
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Scripting Languages

From novice to tech pro — start learning today.