Jump to content

Need product options checkbox from popup for multiple qty with price updates


The_Dude_1978

Recommended Posts

Dear php experts,

 

Please help me out! I've put together a website for my wife and I got almost everything finished, but I cannot find any articles (or know how to find them) how to work with product options. In this case my wife is a photographer.

What she'd like is to have the customers select the size and product of each photo.

 

These are some of the products on photopaper:

10/15 of 10/10          ?  6,00

13/18 of 13/13          ?  7,00

15/22 of 15/15          ?  8,50

 

And these are some of the products on canvas:

30/30    ? 56,-

30/45    ? 73,-

40/40    ? 77,-

40/60    ? 94,-

 

I've been searching for weeks now to look at code snippets that might help, but it's so hard to find.

What it needs to do is when a (multiple) checkbox is selected (rather through a popup(,javascript?)) it updates the total price of that photo item.

Or choosing add another option button sort of.

 

Should data come out of mysql or javascript? What's best practice?

 

Would someone special please be so kind to help this novice out?

 

function getProducts()
{
include 'page_pagination.php';//Include the pagination for THIS page 
//Function to display the products on the front end

//Create the MYSQL db connection
$db = new Connection(DB_HOST, DB_USER, DB_PASS, T4_DB_NAME);



//Set the items variable so that you can add to it in the loop below
$items = '';

//Loop through the mysql results

if( isset( $_SESSION['id'] ) && isset($_SESSION['username']))
{
$sql="SELECT `id`, `first`, `last`, `username`, `email`, `about`, `level` from `users` WHERE `id` = '" . mysql_real_escape_string( $_SESSION [ "id" ]) . "'";
$res=mysql_query($sql);
$row=mysql_fetch_assoc($res);

{

$sql2 = "SELECT `item`, `profile_id`, `title`, `size`, `type`, `thumbnail`, `reference`,`price` FROM user_photos WHERE profile_id = '" . mysql_real_escape_string( $_SESSION [ "id" ]) .  "'";
$res2 = mysql_query($sql2) or die(mysql_error());

'
<link href="paging.css" rel="stylesheet" type="text/css"> 

<table width="" border="0" align="center" cellpadding="3" cellspacing="0"> 
  <tr> 
        <td width="" align="center" class="">'; echo $pagination;'</td>
  </tr>
  <tr> 
        <td align="center" valign="top">';

if ($total_pages == 0) 
        //$total_pages is queried from the include above (page_pagination.php') 
                { 
                //There are no results 
                echo '<p></p><p></p><b>Sorry, there are no product items yet.<b>'; 
                }else{   
                //There are results 
                //$result is queried from the include above (page_pagination.php') 
                while($file = mysql_fetch_array($result))
	{
	$items .= '



	<div class="product">
		<h3>Product: '.stripslashes($file['title']).'</h3>
		<div class="info">
			<a href="'.$_SESSION['username'].'/pics/'.($file['reference']).'" rel="lightbox"><img src="'.$_SESSION['username'].'/pics/thumbs/'.($file['thumbnail']).'" onMouseOver="window.status=\'\';return true" onMouseOut="window.status=\'\'"></a>
			<div class="price">€'.number_format($file['price'], 2).'</div>
			<br><h5>Exclusief 19% BTW<br></h5>
			<a href="addToCart.php?page='.$_GET['page'].'&item='.$file['item'].'"><strong><font color=\"red\">Toevoegen</font></strong></a>
		</div>
	</div>

	';
	}
	}

	echo $items;
	'
	        </td> 
  </tr> 
  <tr> 
        <td> </td> 
  </tr> 
</table> ';

                //End of if statement
}
}
}
function cartExists()
{

//Function returns a bool depending wheather the paypal cart is set or not

if(isset($_SESSION['paypalCart']))
{

	//Exists
	return true;

}
else
{

	//Doesn't exist
	return false;

}

}

function createCart()
{

//Create a new cart as a session variable with the value being an array
$_SESSION['paypalCart'] = array();

}

function insertToCart($productID, $username, $thumbnail, $title, $price, $qty = 1)
{

//Function is run when a user presses an add to cart button

//Check if the product ID exists in the paypal cart array
if(array_key_exists($productID, $_SESSION['paypalCart']))
{

	//Calculate new total based on current quantity
	$newTotal = $_SESSION['paypalCart'][$productID]['qty'] + $qty;

	//Update the product quantity with the new total of products
	$_SESSION['paypalCart'][$productID]['qty'] = $newTotal;

}
else
{

	//If the product doesn't exist in the cart array then add the product
	$_SESSION['paypalCart'][$productID]['item'] = $productID;
	$_SESSION['paypalCart'][$productID]['username'] = $username;
	$_SESSION['paypalCart'][$productID]['thumbnail'] = $thumbnail;
	$_SESSION['paypalCart'][$productID]['name'] = $title;
	$_SESSION['paypalCart'][$productID]['price'] = $price;
	$_SESSION['paypalCart'][$productID]['qty'] = $qty;

}

}

function addToCart()



{

//Function for adding a product to the cart based on that products ID.
//Create the MYSQL db connection
$db = new Connection(DB_HOST, DB_USER, DB_PASS, T4_DB_NAME);

//Check if the ID variable is set
if(isset($_GET['item']) && isset($_SESSION['username']))
{

	//Escape the string from the URL
	$item = mysql_real_escape_string($_GET['item']);
	$username = mysql_real_escape_string($_SESSION['username']);

	//Check if the ID passed exists within the database
	$result = $db->query('SELECT * FROM user_photos WHERE item = "'.$item.'" LIMIT 1');
	$result2 = $db->query('SELECT * FROM users WHERE username = "'.$username.'"');

	//Get the total results of if any product matched the query
	$totalRows = mysql_num_rows($result);

	//If the product ID exists in the database then insert it to the cart
	if($totalRows > 0)
	{

		while($row = mysql_fetch_assoc($result))
		{

			//Check if the cart exists
			if(cartExists())
			{

				//The cart exists so just add it to the cart
				insertToCart($item, $username, $row['thumbnail'], $row['title'], $row['price']);

			}
			else
			{

				//The cart doesn't exist so create the cart
				createCart();

				//The cart is now created so add the product to the cart
				insertToCart($item, $username, $row['thumbnail'], $row['title'], $row['price']);

			}

		}

	}
	else
	{

		//No products were found in the database so notify the user, redirect him and stop the code from continuing
		notify('Sorry, maar er is geen product met dit Item.', 0);
		header("Location: profile.php?page=".$_GET['page']."");
		break;

	}

	//The product was successfully added so set the notification and redirect to the cart page
	notify('Item is toegevoegd aan de winkelwagen.', 1);
	// header("Location: cart.php");
	header("Location: profile.php?page=".$_GET['page']."");
}
else
{

	//No Product with that ID redirect and display message
	notify('Sorry, maar er is geen product met dit Item.', 0);
	header("Location: profile.php?page=".$_GET['page']."");
}

}

function removeFromCart()
{

//Runs when the user presses the remove from cart button

if(isset($_GET['item']))
{

	$productID = $_GET['item'];

	//Check if the product exists within the cart if so follow on
	if(array_key_exists($productID, $_SESSION['paypalCart']))
	{

		//Remove one from the total quantity of products set in the cart
		$newQty = $_SESSION['paypalCart'][$productID]['qty'] - 1;

		//Update the cart quantity
		$_SESSION['paypalCart'][$productID]['qty'] = $newQty;

		//If there are less than 1 in the qty subkey then remove the product from the cart
		if($newQty < 1)
		{

			//Remove the product from the cart
			unset($_SESSION['paypalCart'][$productID]);

		}

		//No Product with that ID redirect and display message
		notify('1 Item verwijdert uit de winkelwagen.', 1);
		header("Location: cart.php");

	}
	else
	{

		//No Product with that ID redirect and display message
		notify('Sorry, maar er is geen product met dit Item.', 0);
		header("Location: profile.php?page=".$_GET['page']."");

	}

}
else
{

	//No Product with that ID redirect and display message
	notify('Sorry, maar er is geen product met dit Item', 0);
	header("Location: profile.php?page=".$_GET['page']."");

}

}

function getShoppingCart()
{

//Function creates the display for the cart

//If the cart exists then follow on
if(cartExists())
{

	//Check if there are any products in the cart by counting the array keys
	if(count($_SESSION['paypalCart']) > 0)
	{

		//The table header html
		$html = '
		<table cellpadding="0" cellspacing="0" border="0">
			<tr>
				<th>Thumbnail</th>
				<th>Item naam</th>
				<th>Prijs</th>
				<th>Hoeveelheid</th>
				<th></th>
			</tr>
		';

		$count = 1;

		//Loop through the items in the paypal cart
		foreach($_SESSION['paypalCart'] as $product)
		{

			$html .= '
			<tr>
				<td width="250"><img src='.$product['username'].'/pics/thumbs/'.$product['thumbnail'].'></td>
				<td width="200">'.$product['name'].'</td>
				<td width="200">€'.number_format($product['price'], 2).'</td>
				<td width="250">'.$product['qty'].'</td>
				<td width="200"><a href="addToCart.php?item='.$product['item'].'">Toevoegen</a> / <a href="removeFromCart.php?item='.$product['item'].'">Verwijderen</a></td>
				<input type="hidden" name="amount_'.$count.'" value="'.$product['price'].'" />
				<input type="hidden" name="quantity_'.$count.'" value="'.$product['qty'].'" />
				<input type="hidden" name="tax_rate_'.$count.'" value="'.TAX.'" />
				<input type="hidden" name="item_name_'.$count.'" value="'.stripslashes($product['name']).'" />
				<input type="hidden" name="item_number_'.$count.'" value="'.$product['item'].'" />
			</tr>
			';

			$count++;

		}

		//HTML for the subrows such as the subtotal, tax and total
		$html .= '
			<tr class="empty">
				<td></td>
				<td></td>
				<td></td>
				<td></td>
				<td></td>
			</tr>
			<tr>
				<td></td>
				<td></td>
				<td></td>
				<td class="bold">Subtotaal</td>
				<td>'.calculateSubtotal().'</td>
			</tr>
			<tr>
				<td></td>
				<td></td>
				<td></td>
				<td class="bold">'.TAX.'% BTW</td>
				<td>'.calculateTax().'</td>
			</tr>
			<tr>
				<td></td>
				<td></td>
				<td></td>
				<td class="bold">Totaal</td>
				<td>'.calculateTotal().'</td>
			</tr>

		</table>



		';

		echo $html;

	}
	else
	{

		//If there are no products then print out a message saying there are no products
		echo '<p>Er zijn momenteel geen producten in uw winkelwagen.</p>';
		unset($_SESSION['paypalCart']);
	}

}
else
{

	//If there are no products then print out a message saying there are no products
	echo '<p>Er zijn momenteel geen producten in uw winkelwagen.</p>';
	unset($_SESSION['paypalCart']);
}

}

function calculateSubtotal()
{

//Set the base variable for the subtotal
$subtotal = 0;

//Loop through the products in the cart
foreach($_SESSION['paypalCart'] as $product)
{

	//Get the total amount of the current product iteration
	$qty = $product['qty'];

	//Get the price of the current product iteration
	$price = $product['price'];

	//Calculate the subtotal
	$subtotal = $subtotal + ($price * $qty);

}

//Create the formatted result for the subtotal
$result = '€'.number_format($subtotal, 2);

return $result;

}

function calculateTotal()
{

//Set the base variable for the total
$total = 0;

//Loop through the products in the cart
foreach($_SESSION['paypalCart'] as $product)
{

	//Get the total amount of the current product iteration
	$qty = $product['qty'];

	//Get the price of the current product iteration
	$price = $product['price'];

	//Calculate the total
	$total = $total + ($price * $qty);

}

//Calculate the tax based on the tax variable
$tax = ($total * TAX) / 100;

//Set the total price including tax
$total = $total + $tax;

//Create the formatted result for the total
$result = '€'.number_format($total, 2);

return $result;

}

function calculateTax()
{

//Set the base variable for the total
$total = 0;

//Loop through the products in the cart
foreach($_SESSION['paypalCart'] as $product)
{

	//Get the total amount of the current product iteration
	$qty = $product['qty'];

	//Get the price of the current product iteration
	$price = $product['price'];

	//Calculate the total
	$total = $total + ($price * $qty);

}

//Calculate the total tax
$tax = ($total * TAX) / 100;

//Create the formatted result for the total
$result = '€'.number_format($tax, 2);

return $result;

}

 

 

Maybe this basic code can perform such a task, but then pulling it and displaying it from a mysql database?

 

<html> 
<script language="javascript"> 
function openwindow() 
{ 
retval=window.showModalDialog("popup.html") 
document.getElementById('text1').value=retval 
} 
</script> 
<body> 
<form name=frm> 
<input name=text1 type=text readonly> 
<input type=button onclick="javascript:openwindow()" value="Open window.."> 
</form> 
</body> 
</html> 

 

<html> 
<head> 
<script language="javascript"> 
function changeparent1() 
{ 
window.returnValue="4.95" 
window.close() 
}
function changeparent2() 
{ 
window.returnValue="19,95" 
window.close() 
} 
function changeparent3() 
{ 
window.returnValue="24,95" 
window.close() 
} 


</script> 
</head> 
<body> 
<form> 
<input type="checkbox" onclick="javascript:changeparent1()" value="30x15">30x15 = ? 4.95<br />
<input type="checkbox" onclick="javascript:changeparent2()" value="30x45">30x45 = ? 19,95<br />
<input type="checkbox" onclick="javascript:changeparent3()" value="45x45">45x45 = ? 24,95

</form> 
</body> 
</html> 

Link to comment
Share on other sites

I'm not entierly sure I got the question, but I would try to add an empty div and populate the value inside that. You would pull the amounts from the database and place them in javascript variables or you can look into AJAX on how to populate the amounts directly from the database. I would go with AJAX if the data display can change often. Otherwise, loading it on page load is fine

 

Hope this helped

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.