Link to home
Start Free TrialLog in
Avatar of shrikanthnk
shrikanthnkFlag for United States of America

asked on

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

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

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.
https://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.
https://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!
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
Avatar of shrikanthnk

ASKER

yes...  Sorry for that..
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
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.
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