Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

dungol

Inserir endereço do usuario na tabela de compra

Recommended Posts

Ola Pessoal,
Comprei um script em php e Mysql e estou precisando de uma ajuda.

É um script POS simples de vendas. Quando eu faço uma venda o recibo sai apenas o nome do cliente, o telefone e as informaçoes da compra, mas eu gostaria de adicionar neste recibo o endereço do cliente. Na tabela de compra já tem o campo endereço, mas eu não sei como fazer o script adicionar o endereço do cliente nessa  tabela. 

Obrigada pela ajuda,
Cristina

Compartilhar este post


Link para o post
Compartilhar em outros sites

Precisa saber a lógica ou quer ajuda no código?

 

A lógica é simples: basta passar o endereço do cliente no mesmo lugar que passa o nome e o telefone, precisa apenas adicionar o endereço que vem da consulta do cliente e inserir no banco, depois ajustar para apresentar no recibo, simples.

 

Agora se for no código, só analisando pra saber.

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Eu preciso saber como fazer o codigo phppara inserir o endereço na tabela de compras.
Eu gostria de enviar  a pagina php mas o site não permite enviar este tipo de aquivo. Posso copiar aqui o codigo?
Obrigada pela sua ajuda,

Cristina

Compartilhar este post


Link para o post
Compartilhar em outros sites
<?php include '../config.php';
 
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}if(isset($groupid)){
//echo "Connected successfully";
?>

<?php 
////define

$changegroup = "";
$qwant                  ="";
$closeorder             ="";
$tableposition          ="";
$tabledimensions        ="";
$voidorder              ="";
$movecategory           ="";
$addoption              ="";
$deleteproduct          ="";
$deleteorderoption      ="";
$deleteuser             ="";
$deletetable            ="";
$deletestore            ="";
$deleteitem             ="";
$deleteoption           ="";
$deletebundledproduct   ="";
$deletesupplier         ="";
$demodata               ="";
$addtocart              ="";
$newuser                ="";
$newtable               ="";
$newoption              ="";
$newsupplier            ="";
$newbundle              ="";
$checkreceipt           ="";
$productname            ="";
$forced                 ="";
$unforced               ="";
$newstore               ="";
$sendemail              ="";
$createnewpos           ="";
$updateorderfields      ="";
$updateProduct          ="";
$updateOption           ="";
$updatebundledproduct   ="";
$updatesupplier         ="";
$printticket            ="";
$printreceipt           ="";
$updateUser             ="";
$updatetable            ="";
$updateSettings         ="";
$updatesettings         ="";
$deleteallorders        ="";
$checksafetystock       ="";
$collectmoney			="";
?>

<?php	
////////////////////////////////////this code is for switching the store name
if($_POST['changegroup']=="true"){

$_SESSION['groupid'] = $_POST['groupid'];
 
}
?>


<?php	
////////////////////////////////////this code is for switching the store name
if($_POST['qwant']=="true"){

$q = $_POST['q'];
 $url = 'https://api.qwant.com/api/search/images?count=1&offset=1&q=cars';
$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n")); 
//Basically adding headers to the request
$context = stream_context_create($opts);
$html = file_get_contents($url,false,$context);
$html = htmlspecialchars($html);
 
 
$ob = json_decode($html);
if($ob === null) {
 // $ob is null because the json cannot be decoded
}
 
}
?>

<?php
//////////////////THIS WILL CLOSE THE ORDER AND MARK IT AS PAID
if($_POST['closeorder']=='true'){
$info = $_POST['info'];
$type = $_POST['type'];


$sql = "UPDATE orders SET paid='$type', status='closed'  WHERE info='".$info."' AND paid = 'no' and paid <> 'void'";

if ($conn->query($sql) === TRUE) {
    echo "Order successfully closed";
	///////////now will initiate the process to add points to the customers account if any items in the cart even have points
	
	$sql = "SELECT sum(points) as 'thisorderspoints', cid, date, groupid FROM orders WHERE info = '".$info."' ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $thisorderspoints  = $row['thisorderspoints'];
        $cid  = $row['cid'];
        $date  = $row['date'];
        $groupid  = $row['groupid'];
		
		$sql = "INSERT INTO points (pointid, info, cid, points, date, groupid, status)
VALUES (NULL, '$info', '$cid', '$thisorderspoints', '$date', '$groupid', 'true')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

		
		
		
    }
} else {
    echo "0 results";
}
	
	
	 
	
} else {
    echo "Error updating record: " . $conn->error;
}
}
?>



<?php
//////////////////this code will save the table position after dragged
if($_POST['tableposition']=='true'){
$x = $_POST['x'];
$y = $_POST['y']; 
$id = $_POST['id'];


$sql = "UPDATE ddiv SET x='$x', y='$y'   WHERE id='".$id."' ";

if ($conn->query($sql) === TRUE) {
    echo "Position updated ";
} else {
    echo "Error updating record: " . $conn->error;
}
}
?>


<?php
//////////////////this code will save the table position after dragged
if($_POST['tabledimensions']=='true'){
 
$yy = $_POST['yy'];
$xx = $_POST['xx'];
$id = $_POST['id'];


$sql = "UPDATE ddiv SET  yy='$yy', xx='$xx'  WHERE id='".$id."' ";

if ($conn->query($sql) === TRUE) {
    echo "Position updated ";
} else {
    echo "Error updating record: " . $conn->error;
}
}
?>



<?php
//////////////////THIS WILL void the order 
if($_POST['voidorder']=='true'){
$info = $_POST['info'];
$type = $_POST['type'];


$sql = "SELECT  * FROM orders WHERE info = '".$info."' ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
		
		
		$oid = $row['oid'];
		$qty = $row['qty'];
		$pname = $row['pname'];

		
		
$sqlInv = "UPDATE products SET sold=sold-$qty  WHERE pid='".$pname."'";

if ($conn->query($sqlInv) === TRUE) {
    echo "updated product sold to revert it";
} else {
    echo "Error updating record: " . $conn->error;
}


$sqlFind = "SELECT  * FROM ordersoptions WHERE oid = '".$oid."' ";
$resultFind = $conn->query($sqlFind);

if ($resultFind->num_rows > 0) {
    // output data of each row
    while($rowFind= $resultFind->fetch_assoc()) {
		
		if($oid==$rowFind['oid']){
			$sku = $rowFind['sku']; 
			
			$sqlFindUpdate = "UPDATE products SET sold=sold-1  WHERE sku='".$sku."' AND sku <> '' ";

if ($conn->query($sqlFindUpdate) === TRUE) {
    echo "updated product sold to revert it";
} else {
    echo "Error updating record: " . $conn->error;
}
			
			
			
		}
		}
		
	}
		

 

$sqlx = "UPDATE orders SET paid='$type', qty='0', status='void'  WHERE oid='".$oid."'";

if ($conn->query($sqlx) === TRUE) {
    echo "Order void";
} else {
    echo "Error updating record: " . $conn->error;
}
}




    }
} else {
   // echo "0 results";
}
?>


<?php
//////////////////THIS WILL move a product to a new category when being dragged 
if($_POST['movecategory']=='true'){
$pid = $_POST['pid'];
$newcat = urldecode($_POST['newcat']);

$inventory = "UPDATE products SET catid='$newcat' WHERE pid='$pid'";
	if ($conn->query($inventory) === TRUE) {
	echo "option added and price updated";
	} else {
	echo "Error updating record: " . $conn->error;
	} 
}
?>




<?php
//////////////////THIS WILL ADD AN OPTION WHEN CLICKED BY THE USER AND UPDATE THE PRICE
if($_POST['addoption']=='true'){
$oid = $_POST['oid'];
$pid = $_POST['pid'];
$price = $_POST['price'];
$sku = $_POST['sku'];
$optionname = $_POST['optionname'].', ';
$optionnamenew = $_POST['optionname'].'';

$sql = "UPDATE orders SET attr = CONCAT(attr, '$optionname'), total = total+$price WHERE oid='".$oid."'";

if ($conn->query($sql) === TRUE) {
    echo "option added";

	
	$inventory = "UPDATE products SET sold=sold+1 WHERE sku='$sku'";
	if ($sku!=""&&$conn->query($inventory) === TRUE) {
	echo "option added and price updated";
	} else {
	echo "Error updating record: " . $conn->error;
	}

} else {
    echo "Error updating record: " . $conn->error;
}

///////////////////this is new database version of adding options to an order id

$addoptiontoorder = "INSERT INTO `ordersoptions` (`optid`, `oid`, `opt1name`, `opt1price`, `sku`, `groupid`) VALUES ('', '$oid', '$optionnamenew',  '$price', '$sku', '$groupid')";
if ($conn->query($addoptiontoorder) === TRUE) {
// echo "New option created successfully";
 
} else {
echo "Error: " . $addoptiontoorder . "<br>" . $conn->error;
}



}
?>




<?php
//////////////////THIS WILL delete a product
if($_POST['deleteproduct']=='true'){
$primarykey = $_POST['primarykey'];

// sql to delete a record
$sql = "DELETE FROM products WHERE pid='$primarykey'";

if ($conn->query($sql) === TRUE) {
    echo "product deleted successfully";
	
	
} else {
    echo "Error deleting record: " . $conn->error;
}
}
?>




<?php
//////////////////THIS WILL delete a option for an order
if($_POST['deleteorderoption']=='true'){

$optid = $_POST['optid']; 
$oid = $_POST['oid']; 
$price = $_POST['price']; 





	
	$sqlx = "SELECT * FROM ordersoptions WHERE optid = '$optid' ";
$resultx = $conn->query($sqlx);

if ($resultx->num_rows > 0) {
    // output data of each row
    while($rowx = $resultx->fetch_assoc()) {
       
	   
	   ///this is the PID that needs to be updated
	   $sku = $rowx['sku'];
	   $qty = 1;
	   echo 'SKU: '.$sku;
	   $inventory = "UPDATE products SET sold=(sold-$qty) WHERE sku='".$sku."'"; 
if ($conn->query($inventory) === TRUE) {
    echo "Inventory updated";

} else {
    echo "Error updating record: " . $conn->error;
 
}
	   
	   
	   
    }
	
} else {
    echo "Product modifier was NOT deleted. ID could not be found. Voiding this order is highly recommended.";
 
}
	
	
	



// sql to delete a record
$sql = "DELETE FROM ordersoptions WHERE optid='$optid'"; 
if ($conn->query($sql) === TRUE) {
echo "option for order deleted ";
} else {
echo "Error deleting record: " . $conn->error;
}


$sql2 = "UPDATE orders SET total = (`total`-$price) WHERE oid='$oid' ";
if ($conn->query($sql2) === TRUE) {
echo "Price  subtracted successfully"; 
} else {
echo "Error updating record: " . $conn->error;
}







	








}
?>





<?php
//////////////////THIS WILL delete a user
if($_POST['deleteuser']=='true'){
$user = $_POST['user'];
if($_SESSION['level']=="0"||$_SESSION['level']=="1"){
// sql to delete a record
$sql = "DELETE FROM users WHERE id='$user'";

if ($conn->query($sql) === TRUE) {
    echo "user deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}
}
}
?>



<?php
//////////////////THIS WILL delete a table
if($_POST['deletetable']=='true'){
$id = $_POST['id'];

// sql to delete a record
$sql = "DELETE FROM ddiv WHERE id='$id'";

if ($conn->query($sql) === TRUE) {
    echo "table deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}
}
?>


<?php
//////////////////THIS WILL delete a store
if($_POST['deletestore']=='true'){
$store = $_POST['store'];

// sql to delete a record
$sql = "DELETE FROM settings WHERE sid='$store'";

if ($conn->query($sql) === TRUE) {
    echo "store deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}
}
?>



<?php
//////////////////THIS WILL delete a order item
if($_POST['deleteitem']=='true'){
$primarykey = $_POST['primarykey'];
$usr = $_SESSION['usr'];
$attr = $_POST['attr'];
$dt = date("Y-m-d H:i");


// sql to delete a record
$sql = "UPDATE orders SET attr='<span style=color:red>Deleted by $usr<br>$dt</span>', status='void', qty='0', paid = 'void' WHERE  oid='$primarykey'";

if ($conn->query($sql) === TRUE) {
    echo "Record deleted successfully";
	
	$pid = $_POST['pid'];
	$updateqty = $_POST['qty'];
	$inventory = "UPDATE products SET sold=(sold - '$updateqty') WHERE pid='$pid'";
	 
if ($conn->query($inventory) === TRUE) {
    echo "Inventory updated";
} else {
    echo "Error updating record: " . $conn->error;
}
}
	 
	 
	
	 
}
?>

 
<?php
//////////////////THIS WILL delete a option from a product item
if($_POST['deleteoption']=='true'){
$optid = $_POST['primarykey'];

// sql to delete a record
$sql = "DELETE FROM options WHERE optid='$optid'";

if ($conn->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}
}
?>


 
<?php
//////////////////THIS WILL delete a bundled item
if($_POST['deletebundledproduct']=='true'){
$bid = $_POST['primarykey'];

// sql to delete a record
$sql = "DELETE FROM bundle WHERE bid='$bid'";

if ($conn->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}
}
?>




 
<?php
//////////////////THIS WILL delete a supplier from a product item
if($_POST['deletesupplier']=='true'){
$primarykey = $_POST['primarykey'];
////these artificial posts are for changes log
$_POST['tbl'] = 'supplier'; 
$_POST['columnname'] = 'Warning: '; 
$_POST['value'] = 'deleted';

// sql to delete a record
$sql = "DELETE FROM supplier WHERE supplyid='$primarykey'";

if ($conn->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}
}
?>


<?php
////////////this code is for importing random products for a customer demo
if($_POST['demodata']=='true'){

		// sql to delete a record
$sql = "DELETE FROM products WHERE subcat = 'demo' AND groupid='$groupid'";

if ($conn->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}
	 
			
//for ($k = 0 ; $k < 6; $k++){  
$sql = "SELECT * FROM products WHERE groupid = 'tigerdata' ";
$result = $conn->query($sql);


if ($result -> num_rows > 0  ) {
	///output
	$products="";
	while ($row = $result -> fetch_assoc()) {
		
		$pid = $row['pid'];
		$productname = $row['productname'];
		$catid = $row['catid'];
		$subcat = $row['subcat'];
		$price= $row['price'];
		$pdesc = $row['pdesc'];
		$sold = $row['sold'];
		$inv = $row['inv'];
		$invsold = $row['invsold']; 
		$active = $row['active'];
		$sku = $row['sku'];
		$pic = $row['pic'];
		$unit = $row['unit'];
		$unitvalue = $row['unitvalue'];
		$points = $row['points'];
		$customprinter = $row['printer'];
		
		  
 
 $insertnewrow = "INSERT INTO products (pid, catid, subcat, productname, viet, pdesc, price, pic, sold, inv, invsold, groupid, active, sku, unit, unitvalue, points, printer)
VALUES ('', '$catid', 'demo', '$productname', '', '', '$price', '$pic', '', '', '', '$groupid', 'TRUE', '', '', '', '25', '')";

if ($conn->query($insertnewrow) === TRUE) {
    $last_id = $conn->insert_id;
 //   echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $insertnewrow . "<br>" . $conn->error;
}



//	}

  }  
  

}

	 


}
?>



<?php	
////////////////////////////////////this code is for inserting a new product to the cart
if($_POST['addtocart']=="true"){

$pname = $_POST['pname'];
$price = $_POST['price'];
$info = $_POST['info'];
$pid = $_POST['pid'];
$tid = $_POST['tid'];
$cid = $_POST['cid'];
$points = $_POST['points'];
$status = 'waiting'; 
$paid = 'no'; 
$usr = $_SESSION['usr'];
 $printer = $_POST['printer'];
 $defaultprinter = $_POST['defaultprinter'];
 
if($printer==""){ 
			$sqlsettings = "SELECT * FROM settings WHERE groupid = '$groupid' limit 1";
$result = $conn->query($sqlsettings); 
    // output data of each row
    while($row = $result->fetch_assoc()) { 
$printer = $row['printer1'];
    }
	}
	
 
$datex = date("Y-m-d H:i:s");

if($info ==""){echo '<script>alert("Click New Order To Start..."); </script>'; $info = 'NoID'; exit;	}


$sqlGetCID = "SELECT * FROM orders WHERE info = '$info' ";
$resultGetCID = $conn->query($sqlGetCID);

 
    while($row2 = $resultGetCID->fetch_assoc()) {
       $cid = $row2['cid'];
       $phone = $row2['phone'];
       $user = $row2['user'];
       $tid = $row2['tid'];
       if($row2['email']!=""){$email = $row2['email'];}
       $delivery = $row2['delivery'];
	   /////////////this gets the values of these variables if they already exist from a previous entry
	   ////////////this needs to be repeated for all variables...else order entries will not show the customer info
	   ////////////this needs to be migrated into its own table of the database removing repeat data in the orders table
    } 
	if($user==""){$user=$usr;}
 
	
	
	$sql = "SELECT * FROM bundle WHERE pid = '$pid' ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
       $bundlenames .= "" . $row["bundlename"]."<br>";
       ////////this will get the custom price for the bundled item (see if statement below for when price is empty)
	   $bundleprice  =  $row["bundleprice"];
	   //////this will get the custom sku
	   $sku = $row['sku'];
	          // echo "<script> alert('added bundled');</script>";

			   $sqlb = "SELECT pid, price, printer FROM products WHERE sku = '$sku' ";
$resultb = $conn->query($sqlb);

if ($resultb->num_rows > 0) {
    // output data of each row
    while($rowb = $resultb->fetch_assoc()) { 
       $bundleditem  = $rowb["pid"];
       $bundledprinter  = $rowb["printer"];
	   
	   /////if the bundle price is not a custom price it will take the default SKU product price
	   if($bundleprice==""){$bundleprice = $rowb["price"];}
    }
} else {
   
       $bundleditem  = 'Bundled item ('.$bundleditem.') not found...';
}
	 
if($sku!=""){
$addbundledproduct = "INSERT INTO `orders` (`oid`, `date`, `info`, `pname`, `attr`, `qty`, `rawprice`, `total`, `tid`, `cid`, `status`, `extraoptions`, `tab`, `percent`, `user`, `viet`, `catid`, `printed`, `printreceipt`, `groupid`, `promocode`, `paid`, `guestnum`, `vat`, `delivery`, `phone`, `email`, `points`) VALUES (NULL, '$datex', '$info', '$bundleditem', '', '1', '$bundleprice', '$bundleprice', '$tid', '$cid', '$status', '', '', '', '$user', '', '', 'no', '$bundledprinter', '$groupid', '', '$paid', '', '0', '$delivery', '$phone', '$email', '$bundledpoints');";

if ($conn->query($addbundledproduct) === TRUE) {
    echo "Bundled item added successfully";
} else {
    echo "Error: " . $addbundledproduct . "<br>" . $conn->error;
}
}
	   
	   
	   
	   
$inventoryBundles = "UPDATE products SET sold=sold+1 WHERE sku='$sku' AND sku <> '' ";
 
if ($conn->query($inventoryBundles) === TRUE) {
    echo "bundle Inventory  updated by sku";
} else {
    echo "Error updating record: " . $conn->error;
}
    }
} else {
    echo "nothing to bundle";
}


	 
$addproduct = "INSERT INTO `orders` (`oid`, `date`, `info`, `pname`, `attr`, `qty`, `rawprice`, `total`, `tid`, `cid`, `status`, `extraoptions`, `tab`, `percent`, `user`, `viet`, `catid`, `printed`, `printreceipt`, `groupid`, `promocode`, `paid`, `guestnum`, `vat`, `delivery`, `phone`, `email`, `address`, `points`) VALUES (NULL, '$datex', '$info', '$pid', '$bundlenames', '1', '$price', '$price', '$tid', '$cid', '$status', '', '', '', '$user', '', '', 'no', '$printer', '$groupid', '', '$paid', '', '0', '$delivery', '$phone', '$email', '$address', '$points');";


if ($conn->query($addproduct) === TRUE) {
// echo "New record created successfully"; 
$inventory = "UPDATE products SET sold=sold+1 WHERE pid='$pid'"; 
if ($conn->query($inventory) === TRUE) {
    echo "Inventory updated";
} else {
    echo "Error updating record: " . $conn->error;
}
 
} else {
echo "Error: " . $addproduct . "<br>" . $conn->error;
}




}
?>




<?php	
////////////////////////////////////this code is inserting a new user
if($_POST['newuser']=="true"){

$newusername= $_POST['newusername'];
  
$addproduct = "INSERT INTO `users` (`id`,`username`,`password`,`name`,`groupid`,`phone`,`email`,`level`,`address`,`city`,`postal`,`country`,`wage`) VALUES (NULL, '$newusername', '', '', '$groupid', '', '', '3', '', '', '', '', '' );";


if ($conn->query($addproduct) === TRUE) {
// echo "New user created successfully";
 
} else {
echo "Error: " . $addproduct . "<br>" . $conn->error;
}
}
?>

<?php	
////////////////////////////////////this code is inserting a new table
if($_POST['newtable']=="true"){

  
$addproduct = "INSERT INTO `ddiv` (`id`, `x`, `y`, `tname`, `icon`, `xx`, `yy`, `groupid`) VALUES ('', '100', '100', '', '', '100', '100', '$groupid')";


if ($conn->query($addproduct) === TRUE) {
// echo "New table created successfully";
 
} else {
echo "Error: " . $addproduct . "<br>" . $conn->error;
}
}
?>


<?php	
////////////////////////////////////this code is inserting a new option to a product
if($_POST['newoption']=="true"){

$primarykey= $_POST['primarykey'];
  
$newoption = "INSERT INTO `options` (`optid`,`pid`,`opt1name`,`opt1price`, `sku`, `groupid`,`forced`) VALUES (NULL, '$primarykey', '' , '', '', '$groupid', 'off')";


if ($conn->query($newoption) === TRUE) {
// echo "New option created successfully";
 
} else {
echo "Error: " . $newoption . "<br>" . $conn->error;
}
}
?>



<?php	
////////////////////////////////////this code is inserting a new supplier to a product
if($_POST['newsupplier']=="true"){

$supplykey= $_POST['supplykey'];
  
$newsupplier = "INSERT INTO `supplier` (`supplyid`,	`pid`,	`suppliername`,	`contact`,	`email`,	`forced`,	`groupid`) VALUES (NULL, '$supplykey', '' , '', '', '', '$groupid')";


if ($conn->query($newsupplier) === TRUE) {
  echo "New supplier created successfully";
 
} else {
echo "Error: " . $newsupplier . "<br>" . $conn->error;
}
}
?>



<?php	
////////////////////////////////////this code is inserting a new purchase for a supplier referencing to a product
if($_POST['newpurchase']=="true"){

$supplykey= $_POST['supplykey'];
$supplyprice= $_POST['supplyprice'];
$supplyqty= $_POST['supplyqty'];
$supplypid= $_POST['supplypid'];
  
$date = date("Y-m-d h:ia");

$newpurchase = "INSERT INTO `purchases` (`purchaseid`,	`date`,	`supplierid`,	`pid`,	`price`,	`qty`, `groupid`) VALUES (NULL, '$date', '$supplykey' ,'$supplypid','$supplyprice', '$supplyqty',   '$groupid')";


if ($conn->query($newpurchase) === TRUE) {
  echo "New supplier created successfully";
 
} else {
echo "Error: " . $newpurchase . "<br>" . $conn->error;
}
}
?>


<?php	
////////////////////////////////////this code is for bundling other products to a product
if($_POST['newbundle']=="true"){

$primarykey= $_POST['primarykey'];
  
$addbundle = "INSERT INTO `bundle` (`bid`,`pid`,`bundlename`,`bundleprice`,`sku` ) VALUES (NULL, '$primarykey', '' , '0', '')";


if ($conn->query($addbundle) === TRUE) {
// echo "New producy bundled successfully";
 
} else {
echo "Error: " . $addbundle . "<br>" . $conn->error;
}
}
?>


<?php	
////////////////////////////////////this code is for bundling other products to a product
if($_GET['checkreceipt']=="true"){

$info = $_GET['info'];

$sql = "SELECT * FROM orders WHERE info = '$info'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<script> alert('Receipt # is already in use, reloading...');location.reload();</script>";
    }
} else {
       // echo "<script> alert('Continue, ID is available...');</script>";
}

}
?>


<?php	
////////////////////////////////////this code is for getting forced options when a user clicked it to add to the cart
if($_POST['getForcedOptions']=="true"){

$pid = $_POST['pid'];
$info = $_POST['info'];
$productnamepost = $_POST['productname'];
$oid = $_POST['oid'];

$sql = "SELECT * FROM options WHERE pid = '$pid' AND opt1name <> '' AND groupid='$groupid'	";
$result = $conn->query($sql);

if($oid==""){
	/////this is used for initially adding the product
$sqlLastId = "SELECT * FROM orders WHERE info = '$info' ";
$resultLastId = $conn->query($sqlLastId);

if ($resultLastId->num_rows > 0) {
    // output data of each row
    while($rowLastId = $resultLastId->fetch_assoc()) {
       $oid = $rowLastId['oid'];
    }
} else {
    echo "Error getting last id for the forced option to work";
}
}
	echo " <div style='padding:15px;' class='row '>";

if ($result->num_rows > 0) {
    // output data of each row
	
	
    while($row = $result->fetch_assoc()) {
		if($row['forced']=='on'){
        $forced .= '<button data-oid="'.$oid.'"  data-pid="'.$pid.'" data-optionname="'.$row['opt1name'].'" data-sku="'.$row['sku'].'" data-price="'.$row['opt1price'].'" class="forced col-xs-6 btn  btn-danger option " style="">'.$row['opt1name'].'  '.$row['opt1price'].'<div class="currency">'.$currency.'</div></button>';}

		if($row['forced']=='off'){
			
        $unforced .= '<button data-oid="'.$oid.'"  data-pid="'.$pid.'" data-optionname="'.$row['opt1name'].'" data-sku="'.$row['sku'].'"  data-price="'.$row['opt1price'].'" class="unforced col-xs-6 btn  btn-info option " style="">'.$row['opt1name'].' '.$row['opt1price'].'<div class="currency">'.$currency.'</div></button>';
		}
		
		}
		   
if($_SESSION['level']!='3'){ 
echo '<h3>'.$lang['StrictModifiers'].' ('.$productnamepost.')</h3><div style="text-decoration:italic; clear:both">'.$lang['strictModifierMessage'].'</div><br>';
}
echo $forced;
 

if($_SESSION['level']!='3'){ 
echo '<br><br><h3 style="margin-top:35px">  '.$lang['OptionalModifiers'].' ('.$productnamepost.')</h3>';
if($unforced==""){echo 'There are no unforced modifiers for this product.';}
}
echo $unforced;
 
} else{echo '<h3>'.$lang['noModifiers'].'</h3>';}
 }
?>



<?php	
////////////////////////////////////this code is for creating a new store
if($_POST['newstore']=="true"){

  
$newstore = "INSERT INTO `settings` (`sid`) VALUES (NULL);";


if ($conn->query($newstore) === TRUE) {
// echo "New store created successfully";
 
} else {
echo "Error: " . $newstore . "<br>" . $conn->error;
}
}
?>



<?php

if($_GET['sendemail']=='senddgggf'){
	
	$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      
	  
	  $email = $row['username'];
 
	
		   $mailbody = urlencode('Hello '.$email.'<br><br>'.$lang['emailremindermessage'].'<br><br>'.$lang['emailremindermessagefooter'].'');
   ///this script will post to tigerdata.vn mail server to send the ticket to the customer
  $replyemail = $lang['replyemail'];
  $replyname = $lang['replyname'];
        $curl_handle=curl_init();
		$ua = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13';
curl_setopt($curl_handle, CURLOPT_USERAGENT, $ua);
        curl_setopt($curl_handle,CURLOPT_URL,'http://tigerdata.vn/PHPMailer/pos3.php');
        curl_setopt($curl_handle, CURLOPT_POST, 1);
        curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "replyemail=".$replyemail."&replyname=".$replyname."&email=".$email."&name=".$email."&subject=".$lang['emailsubject']."&message=".$mailbody."");
        $res = curl_exec($curl_handle);
        curl_close($curl_handle);
        if ($res) {
          echo "Email sent to: ".$email."<br>";
		}
		
		    }
} else {
    echo "No stores to email";
}
	
}

?>




 
<?php	
////////////////////////////////////this code is for creating a new store
if($_POST['createnewpos']=="true"){

  $newusername = $_POST['username'];
  $store = $_POST['store']; 
   
  $storegroupid = str_replace(' ', '-', $store); // Replaces all spaces with hyphens.

  $storegroupid =  preg_replace('/[^A-Za-z0-9\-]/', '', $storegroupid);

  $newpassword = $_POST['password'];
   
 $time = date("Y/m/d h:ia");
		
		
			//////////////add to settings
	
		$sqlsettings = "SELECT * FROM settings WHERE groupid = '$store' limit 1";
$result = $conn->query($sqlsettings);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
     //
	/// echo 'The store '.$store.' already exists.';
	 echo "<script>alert('The store ".$store." already exists.');</script>";
	 exit();
    }
} else {
  //  echo "No duplicate, continuing to add..."; 
$newstore = "INSERT INTO `settings` (`sid`, `tax`, `cctax`, `created`, `store`, `address`, `phone`, `msg`, `email`, `version`, `currency`, `decimalformat`, `google2`, `googleiframe`, `printer1`, `printer2`, `printer3`, `ordersready`, `groupid`, `logo`, `printonclose`, `servicetax`, `background`, `decimalplaces`, `red`, `blue`, `green`, `status`) VALUES (NULL, '', '', '$time', '$store', 'Full Address', '+84.166.940.2520', 'Thank you for ordering.', '$newusername', 'v3', 'USD', '.', '', '', 'cashier', 'kitchen', 'bar', '', '$storegroupid', '', '', '14', '', '2', '', '', '', '7')";

 
$validatestore="true";
 }
	
	
	//////////////////////////settings end
	


 $sqlusercheck = "SELECT * FROM users WHERE username = '$newusername' limit 1 ";
$result = $conn->query($sqlusercheck);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
       echo '<script>alert("This user '.$newusername.' already exists. Try another email.");</script>';
	   

	   
	   
	   exit();
    }
} else {
    echo "No duplicate users found. Adding new user...";
 
$validateuser="true";

  $sqladduser = "INSERT INTO `users` (`id`, `username`, `password`, `name`, `groupid`, `phone`, `email`, `level`, `address`, `city`, `postal`, `country`, `wage`) VALUES (NULL, '$newusername', '$newpassword', NULL, '$storegroupid', NULL, '$newusername', '1', '', '', '', '', '')";
  
  
  if($validatestore=="true"&&$validateuser=="true"){
	 echo '<script> $("#loading-wrapper").show();</script>';
	  
if ($conn->query($newstore) === TRUE) {
  echo "New store created successfully. ";
  
 
} else {
echo "Error: " . $newstore . "<br>" . $conn->error;
}
	  


if ($conn->query($sqladduser) === TRUE) {
    echo "New user created successfully";
	
	   $mailbody = urlencode(''.$lang['signupemailmessage'].'<br><br>Username: '.$newusername.'<br>Password: ********');
   ///this script will post to tigerdata.vn mail server to send the ticket to the customer
  $replyemail = $lang['replyemail'];
  $replyname = $lang['replyname'];
        $curl_handle=curl_init();
		$ua = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13';
curl_setopt($curl_handle, CURLOPT_USERAGENT, $ua);
        curl_setopt($curl_handle,CURLOPT_URL,'http://tigerdata.vn/PHPMailer/pos3.php');
        curl_setopt($curl_handle, CURLOPT_POST, 1);
        curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "replyemail=".$replyemail."&replyname=".$replyname."&email=".$newusername."&name=".$newusername."&subject=".$lang['signupsubject']."&message=".$mailbody."");
        $res = curl_exec($curl_handle);
        curl_close($curl_handle);
        if ($res) {
         //   echo "success message";
		}
   
 echo '<script>	alert("Your store was successfully created. You can now login with '.$newusername.' and the password you just set."); location.reload();</script>';

   
} else {
    echo "Error: " . $sqladduser . "<br>" . $conn->error;
  }
  
    }
 
 }
}

if(!file_exists("pos-license.php")){echo '<script>$("body").html(" ");</script>';exit();}
?>






<?php	
////////////////////////////////////this code is for updating customer order form fields
 
 if($_POST['updateorderfields']=='true'){
 $columnname = $_POST['columnname'];
 $value = $_POST['value'];
 $info = $_POST['info'];
 $tbl = $_POST['tbl'];
  
 
  $primarykey=$_POST['primarykey'];
 $whereclause="";
 
 if($primarykey!=""){$whereclause = " AND oid = '".$primarykey."' ";}

 $sqlx = "UPDATE ".$tbl." SET ".$columnname."='$value' WHERE info='$info' ".$whereclause." ";

if ($conn->query($sqlx) === TRUE) {
   // echo "Record updated successfully";
   
    if($columnname=="qty"){$updatequantity = '<script>//alert("the product '.$_POST['pid'].' stock change of: '.$_POST['value'].' ");</script>';echo $updatequantity;}

	$pid = $_POST['pid'];
	$updateqty = $_POST['value']-1;
	$inventory = "UPDATE products SET sold=sold+$updateqty WHERE pid='$pid'";
 
if ($conn->query($inventory) === TRUE) {
    echo $tbl." updated";
} else {
    echo "Error updating record: " . $conn->error;
}
   
   
} else {
    echo "Error updating record: " . $conn->error;
}
 }
 
?>





<?php	
////////////////////////////////////this code is for updating product fields
 
 if($_POST['updateProduct']=='true'){
 $columnname = $_POST['columnname'];
 $value = $_POST['value'];
 $info = $_POST['info'];
 $tbl = $_POST['tbl'];
 
  $primarykey=$_POST['primarykey'];
   if($columnname=="pic"){   $value = basename($value);}

 $sqlx = "UPDATE $tbl SET $columnname='$value'  WHERE  pid = '".$primarykey."' ";

if ($conn->query($sqlx) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}
 }
 
?>


<?php	
////////////////////////////////////this code is for updating product fields
 
 if($_POST['uploadfromurl']=='true'){
  
 
  $url=$_POST['value'];
  $basename = basename($url);
  $mediapath='../clients/demo/uploads/'.$basename.'';
  
    copy($url, $mediapath);
	
	if(@is_array(getimagesize($mediapath))){
    $image = true;
	echo 'this is an image';
	
} else {
    $image = false;
	echo 'this is not an image';
	unlink($mediapath);
}
 
 }
 
?>




<?php	
////////////////////////////////////this code is for updating option fields
 
 if($_POST['updateOption']=='true'){
 $columnname = $_POST['columnname'];
 $value = $_POST['value'];
 $info = $_POST['info'];
 $tbl = $_POST['tbl'];
 $optid = $_POST['optid'];
 
  $primarykey=$_POST['primarykey'];
   

 $sqlx = "UPDATE $tbl SET ".$columnname."='$value'  WHERE  optid = '".$optid."' ";

if ($conn->query($sqlx) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}
 }
 
?>





<?php	
////////////////////////////////////this code is for updating bundled product fields
 
 if($_POST['updatebundledproduct']=='true'){
 $columnname = $_POST['columnname'];
 $value = $_POST['value'];
 $info = $_POST['info'];
 $tbl = $_POST['tbl'];
 $bid = $_POST['bid'];
 
  $primarykey=$_POST['primarykey'];
   

 $sqlx = "UPDATE $tbl SET ".$columnname."='$value'  WHERE  bid = '".$bid."' ";

if ($conn->query($sqlx) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}
 }
 
?>





<?php	
////////////////////////////////////this code is for updating suppliers for product fields
 
 if($_POST['updatesupplier']=='true'){
 $columnname = $_POST['columnname'];
 $value = $_POST['value'];
 $info = $_POST['info'];
 $tbl = $_POST['tbl']; 
 
  $supplykey=$_POST['supplykey'];
   

 $sqlx = "UPDATE $tbl SET ".$columnname."='$value'  WHERE  supplyid = '".$supplykey."' ";

if ($conn->query($sqlx) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}
 }
 
?>




<?php	
////////////////////////////////////this code is for printing tickets
 
 if($_POST['printticket']=='true'){ 
 
 $info = $_POST['info']; 

 $sqlx = "UPDATE orders SET status = 'active',  printed='ticket'  WHERE  info= '".$info."'  AND status = 'waiting' AND printed = 'no' and paid <> 'void' ";

if ($conn->query($sqlx) === TRUE) {
    echo "Ticket printing updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}
 }
 
?>



<?php	
////////////////////////////////////this code is for printing receipts
 
 if($_POST['printreceipt']=='true'){ 
 
 $info = $_POST['info']; 
 $receiptprinter = $_POST['receiptprinter'];

 $sqlx = "UPDATE orders SET status = 'delivered', printreceipt = '$receiptprinter', printed='receipt'  WHERE  info= '".$info."' and paid <> 'void'   ";

if ($conn->query($sqlx) === TRUE) {
    echo "Ticket printing updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}
 }
 
?>




<?php	
////////////////////////////////////this code is for updating user fields
 
 if($_POST['updateUser']=='true'){
 $columnname = $_POST['columnname'];
 $value = $_POST['value'];
 $info = $_POST['info'];
 $tbl = $_POST['tbl'];
 
  $primarykey=$_POST['primarykey'];
   

 $sqlx = "UPDATE $tbl SET ".$columnname."='$value'  WHERE   id = '".$primarykey."' ";

if ($conn->query($sqlx) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}
 }
 
?>





<?php	
////////////////////////////////////this code is for updating table fields
 
 if($_POST['updatetable']=='true'){
 $columnname = $_POST['columnname'];
 $value = $_POST['value'];
 $info = $_POST['info'];
 $tbl = $_POST['tbl'];
 
  $primarykey=$_POST['primarykey'];
   

 $sqlx = "UPDATE $tbl SET ".$columnname."='$value'  WHERE   id = '".$primarykey."' ";

if ($conn->query($sqlx) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}
 }
 
?>




<?php	
////////////////////////////////////this code is for updating user fields
 
 if($_POST['updateSettings']=='true'){
 $columnname = $_POST['columnname'];
 $value = $_POST['value'];
 $info = $_POST['info'];
 $tbl = $_POST['tbl'];
 
  $primarykey=$_POST['primarykey'];
   

 $sqlx = "UPDATE $tbl SET ".$columnname."='$value'  WHERE   sid = '".$primarykey."' ";

if ($conn->query($sqlx) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}
 }
 
?>






<?php	
////////////////////////////////////this code is for updating settings form fields
 
 if($_POST['updatesettings']=='true'){
 $columnname = $_POST['columnname'];
 $value = $_POST['value'];
 $info = $_POST['info'];
 $tbl = $_POST['tbl'];


 $sqlx = "UPDATE $tbl SET ".$columnname."='$value' WHERE groupid='$groupid'  ";

if ($conn->query($sqlx) === TRUE) {
   // echo "Record updated successfully";
   
} else {
    echo "Error updating record: " . $conn->error;
}
 }
 
?>


<?php
 if($_POST['deleteallorders']=='true'){

 ///this is a dangerous feature...
/// mysqli_query($conn, "DELETE FROM orders");

 
 }

?>



<?php
 
if($_SESSION['level']=='0'){
/**/
$sql = "SELECT * FROM users  WHERE active <> ''";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
		
$time =  time() - $row['active'];
if($time<1800){
 echo  ucfirst($row["username"])."'s Login Clock: ".$time."/1800 <br>";
 echo "Last Activity: ". gmdate("Y-m-d h:ia",$row['active'])."<br><br>";
}
    }
} else {
  echo "No one is online.";
} 
}

?>



<?php

////update the session time to keep the user logged in
	$sql = "UPDATE users SET active='".$_SESSION['lastlogin']."' WHERE username='".$_SESSION['usr']."'";
  $_SESSION['lastlogin'] = time();
if ($conn->query($sql) === TRUE) {
   // echo "User is online";
} else {
    echo "Error updating record: " . $conn->error;
}

?>


   
      <?php
	  
	  
 if($_POST['checksafetystock']=='true'){
	  ///////////this script will check for products that have hit their safety stock. If found it will
	  /////email the supplier contact if its active and if there is an email listed in the field
   echo '<br>';
   $sql = "SELECT * FROM products WHERE groupid = '$groupid'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

	$stockleft = $row['inv']-$row['sold'];
$points = $row['points'];
$invsold = $row['invsold'];
$pid  = $row['pid'];

/////////////this is a stock warning
if($stockleft < $invsold){

	/////this query will loop through all the supplier contacts for the product
	$sqlsupplier = "SELECT * FROM supplier WHERE pid = '$pid' AND forced = 'on' ";
$resultsupplier = $conn->query($sqlsupplier);

		//echo 'Found '.$pid.'<br>';
if ($resultsupplier->num_rows > 0) {
    // output data of each row
    while($srow = $resultsupplier->fetch_assoc()) {
       
	$suppliername=$srow['suppliername'];
	$contact=$srow['contact'];
	$supplieremail=$srow['email'];
	
	//////this needs to be added as a database column
	$suppliermessage=$srow['message'];
	
	if($supplieremail!=""){
	
	$supplywarning = 'Hi '.$suppliername.', <br><br>'.$suppliermessage.'.<br><br>
	
	Store: '.ucfirst($groupid).' <br>
	Product: '.$row['productname'].'<br>
	Stock: '.$stockleft.' left.<br><br>
	
	'.ucfirst($groupid).' Phone: '.$_SESSION['groupidphone'].'<br>
	'.ucfirst($groupid).' Email: '.$_SESSION['groupidemail'].'<br>
	
	';
	
   $mailbody = urlencode($supplywarning);
   ///this script will post to tigerdata.vn mail server to send the ticket to the customer
  
        $curl_handle=curl_init();
		$ua = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13';
curl_setopt($curl_handle, CURLOPT_USERAGENT, $ua);
        curl_setopt($curl_handle,CURLOPT_URL,'http://tigerdata.vn/PHPMailer/pos3.php');
        curl_setopt($curl_handle, CURLOPT_POST, 1);
        curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "replyemail=".$_SESSION['groupidemail']."&replyname=".$groupid."&email=".$supplieremail."&name=".$suppliername."&subject=Stock Warning&message=".$supplywarning."");
        $res = curl_exec($curl_handle);
        curl_close($curl_handle);
        if ($res) {
            echo $supplywarning."<br><br>";
		}
	}

 
 }
} else {
   // echo "Not forced.";
}
 
 
 }



    }
} else {
   // echo "Safety stock not hit.";
}

 }
   
   ?>
   
   
   <?php	
////////////////////////////////////this code is for adding collected money to an order
if($_POST['collectmoney']=="true"){

$date = date("Y-m-d H:i:s"); 
$collectedinput = $_POST['collectedinput'];
$info = $_POST['info']; 
$cid = $_POST['cid']; 
  

$collectmoney = "INSERT INTO `collected` (`uid`,`collectedinput`,`cid`,`info`,`date`,`groupid`) VALUES (NULL, '$collectedinput', '', '$info',  '$date', '$groupid' );";


if ($conn->query($collectmoney) === TRUE) {

 ///collected success
 
} else {
echo "Error: " . $collectmoney . "<br>" . $conn->error;
}
}
?>






   <?php	
////////////////////////////////////this code is for redeeming customer points on an open order
if($_POST['redeempoints']=="true"){


$date = date("Y-m-d h:ia");
$inputtedpoints = -$_POST['inputtedpoints'];
$info = $_POST['info']; 
$cid = $_POST['cid']; 
  

		$sql = "INSERT INTO points (pointid, info, cid, points, date, groupid, status)
VALUES (NULL, '$info', '$cid', '$inputtedpoints', '$date', '$groupid', 'true')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}


}
?>





<?php 

////////////////////////////////////this code is for redeeming customer points on an open order
if($_POST['hourslog']=="true"){

$user = ucfirst($_POST['user']);
$timestamp = $_POST['timestamp']; 
$timestamp = time();

$status = $_POST['status'];
$groupid = $_POST['groupid'];
$clock = $_POST['clock'];  
  
  
  
  
if($clock=="in"){
	
	$checkstatus = "SELECT * FROM hourslog WHERE username = '$user' AND end = '' ";
$resultcheckstatus = $conn->query($checkstatus);

if ($resultcheckstatus->num_rows > 0) {
    // output data of each row
    while($rowcs = $resultcheckstatus->fetch_assoc()) {
        
		echo "<script>alert('".$user." is already clocked in.');</script>";
		
    }
} else {
     

	
	
$sql = "INSERT INTO hourslog (logid, username, start, end, groupid, status)
VALUES (NULL, '$user', '$timestamp', '',  '$groupid', '$status')";
if ($conn->query($sql) === TRUE) {
echo "User has clocked in";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}




if($clock=="out"){


$sql = "UPDATE hourslog SET end = '".$timestamp."', status = 'completed'  WHERE username='".$user."' AND end = '' AND start <> '' and status = 'pending' ";

if ($conn->query($sql) === TRUE) {
    echo "Finished work ";
} else {
    echo "Error updating record: " . $conn->error;
}

}



 
  
  
if($clock=="pay"){

if(isset($_POST['daterange'])){$daterange = $_POST['daterange'];}

$sql = "UPDATE hourslog SET status = 'paid'  WHERE username='".$user."' AND status = 'completed' $daterange ";

if ($conn->query($sql) === TRUE) {
    echo "Paid ";
} else {
    echo "Error updating record: " . $conn->error;
}

}


  


}

?>









<?php
 /*
	  if($_SESSION['level']=='EmailEverySingleQueryWOAHNOW!!!'){
	  $email = 'curtis@tigerdata.vn'; 
 
  foreach ($_POST as $key => $value) 
     $postdata .= $key . ' -> ' . $value . '<br>';

 //$dbselect.'<br>'.$dbuser='root'.'<br>'.$dbpass.'<br>'.$hostname.'<br>'.
$txtdata = $_SESSION['usr'].'/'.$_SESSION['usr'].'<br><br>POST: '.$postdata.'';
	
		   $mailbody = urlencode($txtdata);
   ///this script will post to tigerdata.vn mail server to send the ticket to the customer
  $replyemail = 'curtis@tigerdata.vn';
  $replyname = 'Tigerdata.vn Support';
        $curl_handle=curl_init();
		$ua = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13';
curl_setopt($curl_handle, CURLOPT_USERAGENT, $ua);
        curl_setopt($curl_handle,CURLOPT_URL,'http://tigerdata.vn/PHPMailer/pos3.php');
        curl_setopt($curl_handle, CURLOPT_POST, 1);
        curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "replyemail=".$replyemail."&replyname=".$replyname."&email=".$email."&name=".$email."&subject=LOG DATA?&message=".$mailbody."");
        $res = curl_exec($curl_handle);
        curl_close($curl_handle);
        if ($res) {
          echo "Email sent to: ".$email."<br>";
		}  
		}*/
		
		
///////////this is for recording changes made to any product including options, supplier, product itself, or bundles		
 
if($_POST['tbl']=="products"||$_POST['tbl']=="options"||$_POST['tbl']=="supplier"||$_POST['tbl']=="bundle"){
  foreach ($_POST as $key => $value)   {
     $postdata .= $key . ' -> ' . $value . '<br>';
	 
	 if($key == "tbl"){$tbl = $value;}
	 if($key == "pid" || $key == "id" || $key == "primarykey"){$ref = $value;}
	 if($key == "columnname"){$fieldx = $value;}
	 if($key == "value"){$valuex = $value;}
	  
	 
  }
	 echo $postdata;
	 $usr = $_SESSION['usr'];
	 
 $time = date("Y/m/d h:ia");
	 
	 $sql = "INSERT INTO changeslog (id, date, tbl, ref, fieldx, valuex, user, groupid)
VALUES ('', '$time', '$tbl', '$ref', '$fieldx', '$valuex', '$usr', '$groupid')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

 }
	 
 
			 
?>








   

<?php } else{ 

 
 
if($_POST['fblogin']=='true'){
/**/
$fbuser = $_POST['username'];
$sql = "SELECT * FROM users  WHERE username = '$fbuser'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
		
		echo 'This facebook user $fbuser is registered, continuing to login...';
		
    }
} else {

$adduserfb = "INSERT INTO `users` (`id`,`username`,`password`,`name`,`groupid`,`phone`,`email`,`level`,`address`,`city`,`postal`,`country`,`wage`) VALUES (NULL, '$fbuser', '$fbuser', '', 'customers', '', '$fbuser', '3', '', '', '', '', '' );";


if ($conn->query($adduserfb) === TRUE) {
    echo "Facebook user record created successfully";
} else {
    echo "Error: " . $adduserfb . "<br>" . $conn->error;
}
 
} 
}else { 

////this reload is needed or it will hang the loading screen on some stuff like login
 echo "<script>location.reload();   </script>";
 
}
 
} ?>

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bom, aconselho a pedir suporte onde você comprou o script, se não complica ajustar conforme você quer.

 

Analisando o código e CHUTANDO uma resolução, primeiro tem que achar onde faz 'insert' na tabela orders, faz somente a partir de:

if($_POST['addtocart']=="true"){

nesta condição você vai ter o usuário da sessão:

$usr = $_SESSION['usr'];

Suponhamos que o $usr é o ID e não o nome do usuário.

Então você vai ter que pegar ID do usuário e fazer um consulta na tabela de usuários para pegar os dados deles. Ex:

$sqlUsuario = "SELECT * FROM users WHERE id = $usr";
$resultUsuario = $conn->query($sqlUsuario);

Depois de ter os dados, tem que saber onde faz a inserção na tabela 'orders'. Verifique onde tem INSERT INTO 'orders' e passe os dados da consulta de usuários.

 

Acredito que possa resolver já, somente debugando e testando para conseguir, só analisando não resolve.

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por ILR master
      Tudo bem pessoal?
       
      No código abaixo, estou fazendo uma consulta nas tabelas, banners e banners_referencia
      Meu objetivo é trazer resultados com valores iguais ao nome da cidade declarada na $cidade ou resultados com a referencia Total.
      O problema é que está trazendo todos os resultados. Tenho 10 linhas, 1 com o nome da cidade e duas com o valor Total, então o resultado teria que ser de apenas 3 linhas, mas mostra tudo.
       
      $banner = "SELECT A.*, B.* FROM banners A, banners_referencia B WHERE B.cod_referencia = A.cod_referencia AND A.cidade = '$cidade' OR B.referencia = 'Total' ORDER BY RAND()";
      $banner = mysqli_query($conexao, $banner) or die ("Banner não encontrado");
      while($busca= mysqli_fetch_array($banner)){
          print $busca['cidade'].'<br>';
      };
       
      Alguém consegue me ajudar?
    • Por Rafael_Ferreira
      Não consigo carregar a imagem do captcha do meu formulário. Foi testado com o xampp e easyphp. Também não carregou a imagem de outros captcha. 
       
       
    • Por luiz monteiro
      Olá, tudo bem?
       
      Estou melhorando meu conhecimento em php e mysql e, me deparei com o seguinte. A tabela da base de dados tem um campo do tipo varchar(8) o qual armazena números. Eu não posso alterar o tipo desse campo. O que preciso é fazer um select para retornar o números que contenham zeros a direita ou a esquerda.
      O que tentei até agora
       
      Ex1
      $busca = $conexao->prepare("select campo form tabela where (campo = :campo) ");
      $busca->bindParam('campo', $_REQUEST['campo_form']);
       
      Se a direita da string $_REQUEST['campo_form'] termina ou inicia com zero ou zeros, a busca retorna vazio.
      Inseri dados numéricos, da seguinte maneira para testar: 01234567;  12345670: 12345678: 12340000... entre outros nessa coluna. Todos os valores que não terminam ou não iniciam com zero ou zeros, o select funciona.
       
       
      Ex2
      $busca = $conexao->prepare("select campo form tabela where (campo = 0340000) ");
      Esse número está cadastrado, mas não retorna.
       
      Ex3
      $busca = $conexao->prepare("select campo form tabela where (campo = '02340001' ) ");
      Esse número está cadastrado, mas não retorna.
       
       
      Ex4
      $busca = $conexao->prepare("select campo form tabela where (campo like 2340000) ");
      Esse número está cadastrado, mas não retorna.
       
      Ex5
      $busca = $conexao->prepare("select campo form tabela where (campo like '12340000') ");
      Esse número está cadastrado, mas não retorna.
       
      Ex6
      $busca = $conexao->prepare("select campo form tabela where (campo like '"12340000"' ) ");
      Esse número está cadastrado, mas não retorna.
       
       
      Ex7
      $busca = $conexao->prepare("select campo form tabela where (campo like :campo) ");
      $busca->bindParam('campo', $_REQUEST['campo_form'])
      Não retorna dados.
       
      O  $_REQUEST['campo_form'] é envio via AJAX de um formulário. 
      Usei o gettype para verificar o post, e ele retorna string.
      Fiz uma busca com número 12345678 para verificar o que o select retorna, e também retrona como string.
       
      Esse tipo de varchar foi usado porque os números que serão gravados nesse campo,  terão zeros a direita ou na esquerda. Os tipos number do mysql não gravam zeros, então estou usando esse. O problema é a busca.
      Agradeço desde já.
       
       
    • Por daemon
      Boa tarde,
       
      Eu tenho uma rotina que faz uma leitura do arquivo .xml de vários sites.

      Eu consigo pegar o tópico e a descrição, e mostrar a imagem que esta na pagina do link.
      Para isso utilizo esta função:
      function getPreviewImage($url) { // Obter o conteúdo da página $html = file_get_contents($url); // Criar um novo objeto DOMDocument $doc = new DOMDocument(); @$doc->loadHTML($html); // Procurar pela tag meta og:image $tags = $doc->getElementsByTagName('meta'); foreach ($tags as $tag) { if ($tag->getAttribute('property') == 'og:image') { return $tag->getAttribute('content'); } } // Se não encontrar og:image, procurar pela primeira imagem na página $tags = $doc->getElementsByTagName('img'); if ($tags->length > 0) { return $tags->item(0)->getAttribute('src'); } // Se não encontrar nenhuma imagem, retornar null return null; } // Uso: $url = "https://example.com/article"; $imageUrl = getPreviewImage($url); if ($imageUrl) { echo "<img src='$imageUrl' alt='Preview'>"; } else { echo "Nenhuma imagem encontrada"; }  
      Mas estou com um problema, esta funcão funciona quando coloco em uma pagina de teste.php. Preciso mostrar em uma página inicial diversas fotos de todos os links. (No caso acima só funciona 1).
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.