How do I add lines to a php script to stop users making multiple purchases of the same product?

I'm working on a script which a developer made for me a while ago and I wanted to make some amendments to the purchase page.  It's a site where users can buy and sell downloadable items.  Part of the code stops users if:
a) they don't have enough funds in their account.
b) it's their own file
c) they're not logged in

I want to stop users purchasing the same product twice.

There is a table in the database which contains all the purchase orders, including a payment flag.  The table contains the following fields : porder_id, mid, m_userid, m_price, p_userid, payment_flag.  The payment_flag field is set to either Y or N - I'm thinking that I can use this table to see whether users have already purchased the product.

I could hire a freelancer to do this, but I've been trying to learn PHP for a while so I want to know what to do so I can gain more experience.

Thanks in advance
<? 
session_start();
 
include("includes/class_resizeimg.php");
 
include_once("admin/fckeditor/fckeditor.php");
 
//error_reporting(0);
 
$uid=$_SESSION['USER_ID'];
 
/*
if($_SESSION['USER_ID']=='')
{
	header("location:index.php");
	exit();
}*/
 
$owneruser_id=$_SESSION['USER_ID'];
$mid=base64_decode($_REQUEST['mid']);
 //userid='$uid' and is_approve='N'
 
   if($_POST["btnpurchase_x"]!="")
   {
     $purchaseerror="";
	 $ownerdeposit_amount=$db->get_field("ms_member","deposit_amount","id","$owneruser_id");
	 $m_price= $_POST['music_price'];
	 $m_userid= $_POST['music_userid'];
	 $p_userid=$_SESSION['USER_ID'];
	 
     if($ownerdeposit_amount=="" || $ownerdeposit_amount=="0" || $ownerdeposit_amount=="0.00" || $_POST['music_price'] > $ownerdeposit_amount ){
      $purchaseerror="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<li> Sorry ".$_SESSION['USERNAME'].", you cannot afford this item: it costs £".$_POST['music_price']." and you have £".$ownerdeposit_amount."</li>";
	  $purchaseerror.="<br>To Deposit <a href='deposit.php?aid=dpt' class='textlink'>Click here</a>";
	  }//if
	  else
	  {
	    //purchase process
		  
		      $sql_purchase="insert into ms_purchase_order(`mid`,`m_userid`,`m_price`,`p_userid`)values('$mid','$m_userid','$m_price','$p_userid') ";
		      $res_purchase=$db->insert_data($sql_purchase);
			  $porder_id=mysql_insert_id();
			  if($porder_id >0)
			  {
		        header("location:paypalcheckout.php?mid=$mid&porder_id=$porder_id");
			  }	
	    //purchase process
	  }
  }
 
if($_POST["btncomment_x"]!="")
  {
  $error="";
  if($_POST["txtcomment"]=="" || $_POST["txtcomment"] =="<br>"){
  $error="<li>Content is required</li>";
  }
if($error==""){
 
$comment=addslashes($_POST["txtcomment"]);
$sql_in_comment="insert into ms_comment(`user_id`,`mid`,`comment`,`date`)values('{$_SESSION['USER_ID']}','$mid','$comment',now());";
$res_in_comment=$db->insert_data($sql_in_comment);
    $errormsg="<ul><li><b>Your comment was added </b></li></ul>";
}else{
    $errormsg="<ul><li><b>Please review the following issues that occurred</b></li>". $error."</ul>";
}
  
}
 
 $sql_main="select * from ms_music_upload where mid='$mid' and is_approve='Y'";
 $res_main=$db->select_data($sql_main);
 $description=wordwrap(nl2br(stripslashes($res_main[0]['description'])),65, "<br />");
//wordwrap(nl2br(stripslashes($comment)),20, "<br />")
 $music_price=number_format($res_main[0]['price'], 2);
 $music_name=$res_main[0]['name'];
 $userid=$res_main[0]['userid'];
 $muserid=$res_main[0]['userid'];
 $artname=$db->get_field("ms_member","username","id",$muserid);
 $zip_file=$res_main[0]['zipfile'];
 $previewfile=$res_main[0]['audiofile'];
 $musicfilename=getcwd()."/".$zip_file;
 $cliptype=array();
 
 $cliptype[1]="Music";
 $cliptype[2]="Sound";
/* $zip = new ZipArchive;
//echo "<br>test--".$zip->open($zip_file);
 if ($zip->open($zip_file) === TRUE)
{
	
	$filen="main_file/".$userid."/";
	 $zip->extractTo($filen);
 		$i=0;
		while($zip_root=$zip->statIndex($i))
			{
				
				$n=explode("/",$zip_root["name"]);
								
					if($n[1]!='MusicspiderWatermark.wav' && $n[1]!='')
					{
						$playit=$n[0]."/".$n[1];
						
					}
					
				
$i++;
			}
}
else
{
	$sms="File Not  Available";
}
 
$newplayfile=$filen.$playit;*/
//echo "<br>--".$newplayfile;
 
//$timeoffile=$db->Get_DayHMS();
 
 
if($_REQUEST["flg"]=="del")
  {
   $commentid=base64_decode($_REQUEST["sub"]);
   $sql_del="delete from ms_comment where id='$commentid'";
   $res_del=$db->delete_data($sql_del);
   $msgdel="Comment deleted successfully!";
 
}
 
$sql_comment="select mc.* from `ms_comment` as mc where mc.`mid`='$mid' order by mc.`date` desc";
$res_comment=$db->select_data($sql_comment);
$totalcomment=count($res_comment);
 
    $page = $_REQUEST['page'];  
	$limit = 10;
 
	$total = $totalcomment;
	$pager  = Pager::getPagerData($total, $limit, $page);  
	$offset = $pager->offset;  
	$limit  = $pager->limit;  
	$page   = $pager->page; 
$sql_comment.=" limit $offset,$limit";
$res_comment=$db->select_data($sql_comment);
$totalcomment=count($res_comment);
 
//$_SESSION['USER_ID'];
 
 
ob_start();
include_once("musicdetails_header.php");
$profile_header=ob_get_contents();
ob_get_clean();
 
?>
<script language="javascript" src="includes/jsfunction.js"></script>
<script language="javascript" >
 function flagcom(comid,srcobj)
          {
		  var objdivforwait=document.getElementById("divforwait");
		  var oXmlHttp=createXMLHttp();
          objdivforwait.innerHTML = "<table width='200' border='1' cellspacing='0' cellpadding='0' bgcolor='#FFFFFF'><tr><td><table width='200' border='0' cellspacing='1' cellpadding='3' bgcolor='#FFFFFF'><tr><td><img src='images/wait.gif' width='50' height='50'></td></tr><tr><td class='red'>Process in progress...</td></tr></table></td></tr></table>";
		 
		  objdivforwait.style.left= findPosX(srcobj)+"px";
    	  objdivforwait.style.top = findPosY(srcobj)+"px";
         
		  var act="phpajax.php?clickfor=com&subjectId="+comid;
 
              oXmlHttp.open("get",act,true);
 
              oXmlHttp.onreadystatechange=function()
                                          {
 
                                           if(oXmlHttp.readyState==4)
                                              {
 
                                               if(oXmlHttp.status==200)
	                                              {  
                                         			res=oXmlHttp.responseText;
													result=res.split("#");
													if(result[0]==1)
                                            			{
                                                		  objdivforwait.innerHTML = "<table width='200' border='1' cellspacing='0' cellpadding='0' bgcolor='#FFFFFF'><tr><td><table width='200' border='0' cellspacing='1' cellpadding='3' bgcolor='#FFFFFF'><tr><td><img src='images/wait.gif' width='50' height='50'></td></tr><tr><td class='red'>Flaged inappropriate successfully !</td></tr></table></td></tr></table>";                              
														  srcobj.innerHTML = "Flag as Inappropriate ("+result[1]+")"; 
														  setTimeout("clearAct()",10);
														}else{
														  objdivforwait.innerHTML = "<table width='200' border='1' cellspacing='0' cellpadding='0' bgcolor='#FFFFFF'><tr><td><table width='200' border='0' cellspacing='1' cellpadding='3' bgcolor='#FFFFFF'><tr><td><img src='images/wait.gif' width='50' height='50'></td></tr><tr><td class='red'>try later... </td></tr></table></td></tr></table>";                                                         setTimeout("clearAct()",10); 
														
														}
    	  
                                           		  }
                                               }		
 
                                          };
              oXmlHttp.send(null);
 
		
         }
		 
function clearAct(){
                 
		  var objdivforwait=document.getElementById("divforwait");
              objdivforwait.innerHTML ="";
		      objdivforwait.style.left=0+"px" ;
              objdivforwait.style.top =0+"px";
}		 
 
  function con_msg()
  {
    var al_msg;
	// music_name
	 var musicprice=document.getElementById('music_price').value;
	 var musicname=document.getElementById('music_name').value;
	 
	     al_msg ="You are about to purchase '"+musicname+" '.\n\n";
	     al_msg +="<?=CUREXT?>"+musicprice+" will be deducted from your account.\n\n";
	     al_msg +="By using this site you are agreeing to the terms of access and licensing agreements for items";
		 al_msg +=" purchased on the site. Please make sure you are familiar with these agreements before proceeding.\n\n";
		 al_msg +=" Do you wish to proceed?";
		 return confirm(al_msg);
		
  }//con_msg
 </script>
<script language="javascript">AC_FL_RunContent = 0;</script>
<script src="AC_RunActiveContent.js" language="javascript"></script>
<script type="text/javascript" src="audio-player/audio-player/audio-player.js"></script>  
         <script type="text/javascript">  
             AudioPlayer.setup("audio-player/audio-player/player.swf", {  
                 width: 290  
             });  
         </script> 
<div id="divforwait" style="position:absolute;display:block; z-index:2;left:0px;top:0px;" ></div>
<div style="display:inline; position:absolute; z-index:1"></div>
<table width="100%" border="0" cellspacing="3" cellpadding="2" >
  <tr>
    <td colspan="2" bgcolor="#A2A2A2">
      <?=$profile_header?>
    </td>
  </tr>
  <tr>
    <td >&nbsp;</td>
    <td class="red" >
      <? if($purchaseerror!=""){ echo $purchaseerror;}?>
    </td>
  </tr>
  <tr>
    <td  colspan="2" align="center" valign="top">
      <table width="100%" border="0" cellspacing="0" cellpadding="0" align="center">
        <tr>
          <td  align="left" valign="top">
  		  <p id="audioplayer_1"></p>  
            <script type="text/javascript">  
         AudioPlayer.embed("audioplayer_1", {soundFile: "<?=$previewfile?>", titles: "<?=$music_name?>",  artists: "<?=$artname?>",autostart: "yes"  });           </script> 
			
<?
			echo "<br><br><span style='font-family:Arial;font-size: 12px;font-weight: normal;color: #000000;text-decoration: none;'>The preview contains an audio watermark to stop unauthorized copying. <br>The watermark wont appear on the purchased version.</span>";
; 
			 ?>
         <h1> Details </h1>
            
            <!-- Music Section-->
            <table width="100%" border="0" cellspacing="3" cellpadding="2">
              <tr>
                <td width="20%" valign="top">
                  <table width="50%" border="0" cellspacing="3" cellpadding="2">
                    <tr>
                      <td  valign="top" class="text">
                        <?
							  $uid=$userid;
                              $avatar=$db->get_field("ms_member","avatar","id",$uid);
							   $first_name=$db->get_field("ms_member","first_name","id",$uid);
							   $last_name=$db->get_field("ms_member","last_name","id",$uid);
							 	
								if($avatar!="")
								{
								  $img1=new resize (AVATAR_PATH.$avatar,80,80);
								}
								else
								{
								   echo $img1="<img src='".IMAGE_PATH."/photo.jpg' border='0' />";
								}
							 
							?>
                      </td>
                    </tr>
                    <tr>
                      <td valign="top" class="text">
                        <?=ucfirst($first_name." ".$last_name)?>
                      </td>
                    </tr>
                    <!--<tr>
							<td><img src="<?//=IMAGE_PATH?>/5.gif" border="0"  alt="Author was featured" title="Author was featured"/></td>
							</tr>-->
                  </table>
                </td>
                <td valign="top" class="text">
                  <? ob_start();?>
                  <?
						$COMMENTDATA=$description;
						ob_end_clean();
						include("comment_theam_black.php");
						?>
                </td>
              </tr>
              <tr>
                <td colspan="2" class="text" align="right">
                  <? 	if($totalcomment>0) 
						    {
								$PageURL = "music_details.php?mid=".$_REQUEST["mid"];
								Pager::getPageingLine_pagenum($PageURL,$page,$pager->numPages,$pager->limit);
						     } ?>
                </td>
              </tr>
              <tr>
                <td colspan="2" class="red" align="center">
                  <?=$msgdel?>
                </td>
              </tr>
              <? 
					
 
					for($com_it=0;$com_it < $totalcomment;$com_it++ )
					   {
					 
					$comments=stripslashes($res_comment[$com_it]["comment"]);
					if($_SESSION['USER_ID']==$res_comment[$com_it]["user_id"] || $_SESSION['USER_ID']==$userid)
					  {
					  
					  $delaction="music_details.php?flg=del&sub=".base64_encode($res_comment[$com_it]["id"])."&mid=".$_REQUEST["mid"]."&page=".$_REQUEST["page"];
					  $delacttag="<a href='$delaction' class='textlink' onclick=\"return confirm('Are you sure?');\">Delete this comment</a>";
					
					}else{
					$delacttag="";
					}
					
//				  $flagaction="music_details.php?flg=com&sub=".base64_encode($res_comment[$com_it]["id"])."&mid=".$_REQUEST["mid"]."&page=".$_REQUEST["page"];
                   if($_SESSION['USER_ID']!="")
				     {					
			          $flagtag="<a href='javascript:void(0);' class='textlink' onclick=\"flagcom('{$res_comment[$com_it]["id"]}',this);\">Flag as Inappropriate ({$res_comment[$com_it]["flaged_cnt"]}) </a>";
			 	}
				   
				  $sql_is_purches="select * from `ms_purchase_order` where  `mid`='{$mid}' and `p_userid`='{$res_comment[$com_it]["user_id"]}' and `payment_flag`='Y'";
				   $res_is_purches=$db->select_data($sql_is_purches);
				   if(count($res_is_purches) > 0){
				   $pur_state="Purchased";
				   }else{
				   $pur_state="Not purchased";
				   }
					
					?>
              <tr>
                <td align="left" valign="top">
                  <?=userdetails($res_comment[$com_it]["user_id"]);?>
                </td>
                <td align="left">
                  <?
ob_start();
?>
                  <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td colspan="2" align="right" class="grey_nor_text"><?=$pur_state?></td>
                    </tr>
                    <tr>
                      <td colspan="2">
                        <?=$comments?>
                      </td>
                    </tr>
                    <tr>
                      <td colspan="2" align="left">&nbsp;</td>
                    </tr>
                    <tr>
                      <td colspan="2" align="left" class="grey_nor_text" nowrap="nowrap">Posted
                        :
                        <?=$db->Get_DayHMS($res_comment[$com_it]["date"]);?>
                        &nbsp;
                        <?=$flagtag?>
                        &nbsp;
                        <?=$delacttag?>
                      </td>
                    </tr>
                  </table>
                  <?
$COMMENTDATA=ob_get_contents();
ob_end_clean();
include("comment_theam_gray.php");
?>
                </td>
              </tr>
              <? }?>
              <?
					 if($_SESSION['USER_ID'] != '')
					     {
				    ?>
              <tr>
                <td colspan="2" class="red" align="left">
                  <?=$errormsg?>
                </td>
              </tr>
              <tr>
                <td colspan="2">
                  <fieldset>
                  <legend>Discuss this Item</legend>
                  <form method="post" name="txtcomment">
                    <input type="hidden" name="mid" value="<?=$_REQUEST["mid"]?>" />
                    <table width="100%" border="0" cellpadding="2" cellspacing="2" class="text">
                      <tr>
                        <td><b>Your Comment</b></td>
                      </tr>
                      <tr>
                        <td width="100%">
                          <?
					$sBasePath = "./admin/fckeditor/" ;
					$oFCKeditor = new FCKeditor('txtcomment') ;
					$oFCKeditor->BasePath	= $sBasePath ;
					$oFCKeditor->Value="";
					$oFCKeditor->Create() ;
				?>
                        </td>
                      </tr>
                      <tr>
                        <td>
                          <input type="image" src="<?=IMAGE_PATH?>/post-comment.jpg"  name="btncomment" value="Post Comment" />
                        </td>
                      </tr>
                    </table>
                  </form>
                  </fieldset>
                </td>
              </tr>
              <? } ?>
            </table>
            <!-- Music  Section-->
          </td>
          <td align="right"  width="25%" valign="top">
            <!-- Book Mark Section-->
            <table width="100%" border="0" cellspacing="3" cellpadding="2">
              <tr>
                <td  height="50px" align="center">
                  <? ob_start();?>
                  <form method="post" name="frmpurchase" action="">
                    <input type="hidden" name="music_price" id="music_price" value="<?=$music_price?>">
                    <input type="hidden" name="music_userid" id="music_userid" value="<?=$muserid?>">
                    <input type="hidden" name="music_name"  id="music_name" value="<?=$music_name?>">
                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td class="text11bold" align="center">
                          <?
									
									echo "<h2>".CUREXT." ".$music_price."</h2>";
									?>
                        </td>
                      </tr>
                      <? if($_SESSION['USER_ID']!=$userid && $_SESSION['USER_ID']!="") {?>
                      <tr>
                        <td align="center" >
                          <input type="image" src="<?=IMAGE_PATH?>/purchase.jpg"  name="btnpurchase" value="Purchase" onclick="return con_msg();"  />
                        </td>
                      </tr>
                      <? } else if( $_SESSION['USER_ID']==""){?>
                      <tr>
                        <td align="center" class="red" >
                          <input type="image" src="<?=IMAGE_PATH?>/purchase.jpg"  name="btnpurchase1" value="Purchase" onclick="alert('Please login to purchase.'); return false;"  />
                        </td>
                      </tr>
                      <? }else{?>
                      <tr>
                        <td align="center" class="red" >
                          <input type="image" src="<?=IMAGE_PATH?>/purchase.jpg"  name="btnpurchase1" value="Purchase" onclick="alert('This is your own file!'); return false;"  />
                        </td>
                      </tr>
                      <? }?>
                    </table>
                  </form>
                  <?
							$rightHeading="Purchase Item";
							$rightdisplay=ob_get_contents();
							ob_end_clean();
							include("right_theme.php");
							?>
                </td>
              </tr>
              <tr>

Open in new window

miskodiscoAsked:
Who is Participating?
 
Ray PaseurConnect With a Mentor Commented:
A quick look at this shows me that you might want to hire the developer ASAP.  Apparently, the code will update the data base on the basis of information contained in $_REQUEST.  That means I can go to your web page and put things into the URL, and cause a data base update.  This violates the rules of the WWW, which explicitly forbid changing the data model on the basis of a URL GET string.  There are search engines that prefetch URLS, and one of them could be trouble for you some day.

When you hire your developer, insist that (s)he put some comments into the code.

For a really good "learning PHP" resource, get this book:
http://www.sitepoint.com/books/phpmysql1/

It has excellent examples that will put you far ahead in just a few weeks of study.

Best regards, ~Ray
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.