Jump to content

Adding an item/product to a cart just for theory


j.smith1981

Recommended Posts

I am really struggling how to think of adding multiple products to a cart.

 

I presume adding them to a sessions the best way to go about this, going by all the tutorials that I have seen, however.

 

How would I actually go about doing it so that each time a user clicks add, it adds an item to a cart?

 

I really am struggling to get my head around this, just the theoretical steps I am asking for, no real code (I would rather learn the theory and then at least attempt it myself), the best way of me learning from my problems I think, it's worked numerous times in the past for myself.

 

If I do get stuck I will post the next one in the coding help part of this forum.

 

Thanks and I appreciate any replies in advance,

Jez.

Link to comment
Share on other sites

The simplest way, for me, is to have a Cart object which can contain any number of Product objects.  When you add a Product, simply have the Cart check to see if a Product of that type already exists.  If so, increase the quantity by 1.  If not, add all of the Product info.

 

This makes it easy to iterate over the items, too, for display and figuring out prices.

Link to comment
Share on other sites

That is fair enough, am I allowed though to show you what I have done in procedural for now?

 

I just wanted to create both solutions (the one I have done is really not that elegant what so ever though, so I apologise for its crudeness), am I allowed to post code in here or is that best avoided?

 

This is my ideal learning curve, I mean do one in complete procedural vs OOP so to speak, I thought that's probably best suited for my learning style, since yes as I said above, thats when things start to make sense as such.

 

Can I post code in here at all?

 

Thanks and I look forward to a reply,

Jez.

Link to comment
Share on other sites

Yeah, you can post code here.

 

If you're doing it procedurally, have your Cart be an array (which is what the internals of a Cart class would contain anyway).  Each Product could also be an array, where its keys represent its properties.  So, you could have something like:

 

$cart = array();

$screwdriver = array('Name' => 'Screwdriver', 'Price' => 2.34, => 'Quantity' => 1);
$cart[] = $screwdriver;

 

From there, it's easy to check for an existing Product (in this case, a screwdriver), calculate the total price of both a quantity of individual Products and the total price of the entire Cart, and to display it all on the screen.

Link to comment
Share on other sites

Ok this is my logic at the moment, its really not that good but it works somewhat, just not got around to actually adding a product to my cart yet, but working on that, going to have a go at your tips above.

 

Here it is then:

<?php

ini_set('display_errors',1);

$dbhost = 'localhost';
$dbuser = 'mydbuser';
$dbpassword = 'mypassword';
$dbname = 'ecommercev1';

$connect = mysql_connect($dbhost,$dbuser,$dbpassword)  or die (mysql_error());

if($connect){
$select = mysql_select_db($dbname,$connect) or die (mysql_error());

if($select){

function checkProduct($productid)
{
	$sql = mysql_real_escape_string("SELECT *  FROM products WHERE id = $productid");
	$result = mysql_query($sql);

	if(mysql_num_rows($result) > 0){

		// if product exists still?
		return true;

	} else {

		// if it doesnt!
		return false;

	}

}

function sessionStart()
{
	session_name("add_to_cart");
	session_start();
}

	$sql = mysql_real_escape_string("SELECT * FROM products");

	$result = mysql_query($sql);

	// $products = array();
	printf("<table>
	<tr>
	<td>Product</td>	<td>Description</td>	<td>Price</td>	<td></td>
	</tr>
	");
	while($row = mysql_fetch_array($result)) {

		printf("<tr>
		<td>%s</td>	<td>%s</td>	<td>%.2f</td>
		<td><a href=\"index.php?add=%d\">Add to Cart</a></td>
		</tr>

		",$row[1],$row[2],$row[3],$row[0]);

	# this is just for the fun of it!
	/* $products = array(

		$products["id"] = $row[0], // sets the id of the product!
	       
		array(
			$products["productcode"] = $row[1],
			$products["productdescr"] = $row[2],
			$products["price"] = $row[3]
			)
		); */


	} 

	printf("</table>");

	//keep it contained within $connect = true?
	if(array_key_exists('add',$_GET)){ // if add to cart has been started?		

		$productid = $_GET['add'];

		// start session?
		if(session_id() == ''){

			// if session id doesnt exist?
			sessionStart();
			$productcheck = checkProduct($productid);


		} else {

			$productcheck = checkProduct($productid);

		}

		if($productcheck == true) {

			// now do add product to cart:


		}
	}
}
}

 

I just thought for now to keep it on one single page and then I will of course split it up into seperate script files, but just wanted to keep it in the same page for now, until I can get the basic functionality working.

 

Thanks for your help though going to keep on with this, it's finally making sense what I am doing, of course if you want to show me better ways of doing what I have done, I am all ears.

 

I dont think this is bad at all since all of this is mainly going off tips from other sites and using my own programming common sense but I am sure it can be improved considerably.

 

Thank you,

Jez.

 

PS the bit for the fun of it, thats commented out, just wanted to see if I could get multi dimensional arrays working with a database, going off my own logic, then I thought there really is no point in using that since its already using an array to show the values when I get the data out of the database, so commented it out for future ref, I will make a one script file as an example of how to go about it. and then remove it from this script.

Link to comment
Share on other sites

Just to note, right now your syntax is messy, as you define functions within an if-conditional.  Functions should be defined separately from code that's actually supposed to invoke them.  They can be in the same file, but shouldn't be defined in another language structure like an if, or a loop.

Link to comment
Share on other sites

Ah right thats fair enough then.

 

I wasn't then really making sure of anything like that, but its incredibly messy to be fair, I mean as I said I will seperate the files out as I get sections of this finished.

 

I have just moved them to the top below the error ini_set part, like so:

 

<?php

ini_set('display_errors',1);

function checkProduct($productid)
{
	$sql = mysql_real_escape_string("SELECT *  FROM products WHERE id = $productid");
	$result = mysql_query($sql);

	if(mysql_num_rows($result) > 0){

		// if product exists still?
		return true;

	} else {

		// if it doesnt!
		return false;

	}

}

function sessionStart()
{
	session_name("add_to_cart");
	session_start();
}


$dbhost = 'localhost';
$dbuser = 'mydbuser';
$dbpassword = 'mypassword';
$dbname = 'ecommercev1';

$connect = mysql_connect($dbhost,$dbuser,$dbpassword)  or die (mysql_error());

if($connect){
$select = mysql_select_db($dbname,$connect) or die (mysql_error());

if($select){

	$sql = mysql_real_escape_string("SELECT * FROM products");

	$result = mysql_query($sql);

	// $products = array();
	printf("<table>
	<tr>
	<td>Product</td>	<td>Description</td>	<td>Price</td>	<td></td>
	</tr>
	");
	while($row = mysql_fetch_array($result)) {

		printf("<tr>
		<td>%s</td>	<td>%s</td>	<td>%.2f</td>
		<td><a href=\"index.php?add=%d\">Add to Cart</a></td>
		</tr>

		",$row[1],$row[2],$row[3],$row[0]);

	# this is just for the fun of it!
	/* $products = array(

		$products["id"] = $row[0], // sets the id of the product!
	       
		array(
			$products["productcode"] = $row[1],
			$products["productdescr"] = $row[2],
			$products["price"] = $row[3]
			)
		); */


	} 

	printf("</table>");

	//keep it contained within $connect = true?
	if(array_key_exists('add',$_GET)){ // if add to cart has been started?		

		$productid = $_GET['add'];

		// start session?
		if(session_id() == ''){

			// if session id doesnt exist?
			sessionStart();
			$productcheck = checkProduct($productid);


		} else {

			$productcheck = checkProduct($productid);

		}

		if($productcheck == true) {

			// now do add product to cart:
			echo "Now add to cart";


		}
	}
}
}

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.