Jump to content

Update and redirect


himesh
 Share

Recommended Posts

HiI am trying to get my shopping cart to update the quantity value if there is already an item in the basket with the same model number. Instead it keeps adding another of the same item. Also the redirect, I have tried to do it using the header location but im guessing this is not working as it is not at the top? Here is my code.

<?php require_once('Connections/conn_comm.php'); ?><?phpif (!isset($_SESSION['MM_Username'])) {  session_start();}if (!function_exists("GetSQLValueString")) {function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {  if (PHP_VERSION < 6) {	$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;  }  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);  switch ($theType) {	case "text":	  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";	  break;		case "long":	case "int":	  $theValue = ($theValue != "") ? intval($theValue) : "NULL";	  break;	case "double":	  $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";	  break;	case "date":	  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";	  break;	case "defined":	  $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;	  break;  }  return $theValue;}}$colname_addcart = "-1";if (isset($_GET['productID'])) {  $colname_addcart = $_GET['productID'];}mysql_select_db($database_conn_comm, $conn_comm);$query_addcart = sprintf("SELECT manufacturer, modelnumber, price FROM tblproduct WHERE productID = %s", GetSQLValueString($colname_addcart, "int"));$addcart = mysql_query($query_addcart, $conn_comm) or die(mysql_error());$row_addcart = mysql_fetch_assoc($addcart);$totalRows_addcart = mysql_num_rows($addcart);//mysql_select_db($database_conn_comm, $conn_comm);//$query_cart = sprintf("SELECT * FROM tblcart WHERE productID = %s"); //$cart = mysql_query($query_cart, $conn_comm) or die(mysql_error());//$row_cart = mysql_fetch_assoc($cart);//$totalRows_cart = mysql_num_rows($cart);?><?php 		if ( $row_addcart['quantity'] > 1 ){			mysql_query("UPDATE tblcart						SET quantity = quantity +1						WHERE modelnumber = {$row_addcart['modelnumber']}");}		else { $insertSQL = sprintf("INSERT INTO tblcart (manufacturer, modelnumber, quantity, price, username) 							VALUES ('$row_addcart[manufacturer]', '$row_addcart[modelnumber]', '1', '$row_addcart[price]', '$_SESSION[MM_Username]')");	  header( 'Location: http://www.himeshs.co.uk/communicate/basket.php' );//if ($insertSQL) {//	$message  = 'Invalid query: ' . mysql_error() . "\n";//	$message .= 'Whole query: ' . $insertSQL;//	die($message);//}		mysql_select_db($database_conn_comm, $conn_comm);$Result1 = mysql_query($insertSQL, $conn_comm) or die(mysql_error());}	echo $insertSQL;?><?phpmysql_free_result($addcart);?>

Thanks

Link to comment
Share on other sites

I would use a loop check the items already in the cart, and check to see if the item being added already exists, and if it does increase the number of them by one.

Link to comment
Share on other sites

Hi, thanks for the reply but will it not work with an if statement? As I have retrieved all where the item number is the number that has been parsed into it from the previous page and its the

		if ( $row_cart['quantity'] > 1 ){

line which is causing problems as it keeps adding another single item into the cart. Thanks

Link to comment
Share on other sites

Hi, thanks for the reply but will it not work with an if statement? As I have retrieved all where the item number is the number that has been parsed into it from the previous page and its the
		if ( $row_cart['quantity'] > 1 ){

line which is causing problems as it keeps adding another single item into the cart. Thanks

Most likely the IF statement is not true. Output $row_cart['quantity'] to the page and see what you have.
Link to comment
Share on other sites

and you want to check for more than the quantity, don't you? If it is has more than one item, check through the length of all items in the cart, by comparing their ID or whatnot, and then make the appropriate calculations.

Link to comment
Share on other sites

Most likely the IF statement is not true. Output $row_cart['quantity'] to the page and see what you have.
I got it to print it off and it knows that there is 1 as the quantity, I even got it to check the model number and that checks out too :) I tried adding another item into the basket and the correct text prints to screen too
and you want to check for more than the quantity, don't you? If it is has more than one item, check through the length of all items in the cart, by comparing their ID or whatnot, and then make the appropriate calculations.
Yeah, I thought the > 1 would have solved that but it hasn't lol. Have I not already compared their ID's with the SQL statement?
Link to comment
Share on other sites

yeah, that just checks there's already something in the cart. within that you should have another loop which checks the item being added to items already in the cart and if they match, then increase the quantity of that item, rather than just adding it to the overall list of items in the cart.

Edited by thescientist
Link to comment
Share on other sites

Ive changed the code to this but its still not working. Wasn't sure how to use a for loop as it needed an initialising counter or something =s

	if ( '$row_cart[quantity]' > 1 ){			if ('$row_addcart[modelnumber]' == '$row_cart[modelnumber]'){			mysql_query("UPDATE tblcart						SET quantity = (quantity + 1)						WHERE modelnumber = {'$row_addcart[modelnumber]'}");}}

Link to comment
Share on other sites

you need to use a for loop instead of a second if statement, based on the length of the items in the cart, and then check that with the if statement like you are doing.pseudo-code

for(var i = 0; i<cart.length; i++){  if(this.cartItem.modelNumber == cart[i].modelNumber){	//update cart[i]'s quantity += 1  };};

sorry, that's more in a javascript context, but you should get the idea

Link to comment
Share on other sites

Ive changed it to this and now its not adding anything to the cart at all, even another one. Can't see what is going wrong =s im guessing I've missed something simple!

for ($count = 0; $count < $lengths; $count += 1){			if ('$row_addcart[modelnumber]' == '$row_cart[modelnumber]'){			mysql_query("UPDATE tblcart						SET quantity = (quantity + 1)						WHERE modelnumber = {'$row_addcart[modelnumber]'}");			header( 'Location: http://www.himeshs.co.uk/communicate/basket.php' );}else { $insertSQL = sprintf("INSERT INTO tblcart (productID, manufacturer, modelnumber, quantity, price, username) 							VALUES ('$row_addcart[productID]', '$row_addcart[manufacturer]', '$row_addcart[modelnumber]', '1', '$row_addcart[price]', '$_SESSION[MM_Username]')");	header( 'Location: http://www.himeshs.co.uk/communicate/basket.php' );}

Link to comment
Share on other sites

Ive tried it for the total number of rows too but this is not working either, Im guessing the for loop isn't working
And how has guessing worked out for you so far?If this is your loop, and you're wondering if it's working:for ($count = 0; $count < $lengths; $count += 1){...}Why not verify that instead of guessing? Have you printed $lengths to see what the value is? Have you added an echo statement inside the loop to see how many times it runs? What about this line:if ('$row_addcart[modelnumber]' == '$row_cart[modelnumber]'){That's never going to be true, because the string '$row_addcart[modelnumber]' is not equal to the string '$row_cart[modelnumber]', and since you're comparing literal strings there then that if statement will never be true. So, it's always going to go down to the else:
else { $insertSQL = sprintf("INSERT INTO tblcart (productID, manufacturer, modelnumber, quantity, price, username) 							VALUES ('$row_addcart[productID]', '$row_addcart[manufacturer]', '$row_addcart[modelnumber]', '1', '$row_addcart[price]', '$_SESSION[MM_Username]')");	header( 'Location: http://www.himeshs.co.uk/communicate/basket.php' );}

Look at what you're doing there. First, you create a query, then you redirect. You don't actually run the query though, you just create it, then redirect.So, you've built a loop that will keep creating queries and redirecting. You can guess all you want about why it's not working, but it's much more effective to actually understand what the code is doing and figure out why it's doing what it is.

Link to comment
Share on other sites

Evidently the "guessing" has not worked out in my benefit so far. Lengths when printed equals Array, which is obviously not right. The Loop therefore runs 0 times. However when total rows of the cart is printed, it knows that there is one item in the cart but still the loop runs 0 times.Okay, how would it be possible to compare if the model numbers of the product being added into the cart and the model number of an item number in the cart already and if they are the same then the code to be executed?I have copied the $insertSQL code from a previous post and that works, this code I am currently attempting to edit is a copy of the working code.

Link to comment
Share on other sites

I would refer you to my earlier psuedo code post.Use whatever code you have to get the current item, then take the carts length, loop through it, and within that check that the item being added, if its modelNumber is equal to the current cart Item's modelNumber that's being checked with the loop.

Edited by thescientist
Link to comment
Share on other sites

By the length of the cart, do you mean the total number of rows in the cart? As when I am doing

$lengths = mysql_fetch_lengths($cart);

it fetches the length of whatever is in the field. When I printed what it retrieved, I got this

Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 1 [4] => 3 [5] => 6 )

Which is correct as the first field contains the productID, the second contains the manufacturer (in this case LG), the third contains the modelnumber (BL40), the 4th contains the quantity and the last contains the username. I finally understand what you are saying now about I need to get the current row of the table and check the field against that row but i didnt think it was possible to do something like this

if ('$row_addcart[productID]' == '$row_cart[$count][productID]')

. Also I have changed from model number to product ID as the ID is a numerical value and the model number can be both text and numerical. I have also made an error and just noticed that as the cart will be used by different users, the username has to remain unique and with the for loop searching for just the productID, im assuming it will not take into consideration the username also.

Link to comment
Share on other sites

by length i mean the all the items which might already be in the cart, which is what you want to check the current item against to see if any of the ID's (or whatever it is your checking for) match

Link to comment
Share on other sites

if ('$row_addcart[productID]' == '$row_cart[$count][productID]')
I pointed it out before, but you are not comparing the value of $row_addcart['productID'] with $row_cart[$count]['productID']. You are comparing the literal strings "$row_addcart[productID]" and "$row_cart[$count][productID]", not the values of those variables.
Link to comment
Share on other sites

by length i mean the all the items which might already be in the cart, which is what you want to check the current item against to see if any of the ID's (or whatever it is your checking for) match
This part is still confusing me as no matter how many times I read it, I interpret this as total rows :)
I pointed it out before, but you are not comparing the value of $row_addcart['productID'] with $row_cart[$count]['productID']. You are comparing the literal strings "$row_addcart[productID]" and "$row_cart[$count][productID]", not the values of those variables.
Would it be correct to assign the $row_addcart[productID] and $row_cart[productID] to variables and then compare these? Or would that be the same as what I am currently doing?
Link to comment
Share on other sites

Ahhh i see, so it would be correct to do the following

if ($row_addcart[productID] == $row_cart[productID])

or

if ($row_addcart['productID'] == $row_cart['productID'])

If you had not said no quotes, i would have tried the latter as every other time I have had quotes at least around the part in the [].

Link to comment
Share on other sites

Yes, the latter is correct. The name of the array index is in fact a string, so it should be quoted. If the array was numerically indexed, you would not quote the number. If you print the variable in a string or use it in a SQL query you should still quote the index:

$sql = "... WHERE id = {$row_addcart['productID']}";

Other forms may work, but they're not technically correct.

Link to comment
Share on other sites

This part is still confusing me as no matter how many times I read it, I interpret this as total rows :)
rows? Now I don't know what you mean.someone has item(s) in their cart. This now creates an array, called cart, with indexes, of items, each with their own properties, like description, productID, price, quantity, etc.Now someone adds a new item by clicking on "add to cart", or whatever. What you first want to do is check if this new item already exists in the cart, (by checking the new items productID vs. the current cart's array of items, and their productID's) so you just increment an item already in the cart's quantity, instead of just adding it as a completely unique item. right?
Link to comment
Share on other sites

ok, well that would make sense then. I guess just use what is most appropriate given your script convention. Something along the lines of the logic is whats most important. Perhaps I'm too object-oriented, as I would have an array of objects wherein I could access their various properties by using a numeric index.

Link to comment
Share on other sites

Sorted it now, this is how it reads now.

<?php 		if ($row_addcart['productID'] == $row_cart['productID']){						if ($row_addcart['quantity'] > $row_cart['quantity']) {					$add = mysql_query("UPDATE tblcart				SET quantity = `quantity` + 1				WHERE productID = '$row_cart[productID]'");			}						else { header( 'Location: http://www.himeshs.co.uk/communicate/sorrystock.php' ); }	}else { $insertSQL = sprintf("INSERT INTO tblcart (productID, manufacturer, modelnumber, quantity, price, username) 						VALUES ('$row_addcart[productID]', '$row_addcart[manufacturer]', '$row_addcart[modelnumber]', '1', '$row_addcart[price]', '$_SESSION[MM_Username]')");mysql_select_db($database_conn_comm, $conn_comm);$Result1 = mysql_query($insertSQL, $conn_comm) or die(mysql_error());header( 'Location: http://www.himeshs.co.uk/communicate/basket.php' );}?>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...