Jump to content

how to insert multiple rows into mysql


garevn

Recommended Posts

Atm i have almost complete the insert page just 2 things left and need some help.my insert page looks like

<?phpsession_start();$productid=$_SESSION['productid'] ;$pricetotal=$_SESSION['pricetotal'] ;$price=$_SESSION['price'] ;$cartTotal=$_SESSION['cartTotal'] ;$quantity=$_SESSION['quantity'] ;$MM_Username = $_SESSION['MM_Username'];$quantity=$_SESSION['quantity'];  $con = mysql_connect("localhost","root",""); if (!$con)   {   die('Could not connect: ' . mysql_error());   } mysql_select_db("mypc", $con); $sql1="INSERT INTO sales(address, paymethod, creditcard,cardtype,username,cartTotal,phone) VALUES('$_POST[address]','$_POST[RadioGroup1]','$_POST[pass]','$_POST[type]','$MM_Username','$cartTotal','$_POST[phone]')";if (!mysql_query($sql1,$con))   {   die('Error: ' . mysql_error());   }    $sql2="INSERT INTO orders(unitprice,pricetotal,quantity,productid ) VALUES('$price','$pricetotal','$quantity','$productid')";if (!mysql_query($sql2,$con))   {   die('Error: ' . mysql_error());   }       mysql_close($con) ?>

1--> Atm sql2 insert only the last product's id at the table.I need to insert all products chosen by the user.If for example made 10 selections then i insert all 10 rows into mysql2--> I want to display a message to him like "the processing was successfull" but in the same page. Atm when i insert the products i see a blank page or a message which i removed.

Link to comment
Share on other sites

You're not getting more than one product. If the data in $_SESSION are arrays, like if $_SESSION['productid'] is an array, then you can loop through it and insert a row for each ID. How are you setting the session? Are all of your fields named the same thing?It's common to have the page redirect to a thank you page or other page to show a message. That will be better than printing the message on the same page so that they can't hit refresh and cause everything to happen again. If you redirect then refreshing will only reload the redirected page, not the page that inserted everything into the database.

Link to comment
Share on other sites

Its a cart which the user choose his products and i want to save those products into a table.i use this in cart page$_SESSION['productid'] = $productid;I tried this as loop but i get an error on foreach

foreach ($_SESSION['productid'] as $value)   { echo  $sql2="INSERT INTO orders(unitprice,pricetotal,quantity,productid ) VALUES('$price','$pricetotal','$quantity','$value')";if (!mysql_query($sql2,$con))   {   die('Error: ' . mysql_error());   }    }

Link to comment
Share on other sites

you are getting a error because probably $_SESSION['product_id'] is not an array. when you set the product in a cart store it in an array. EG. $_SESSION['mycart'] now $_SESSION['mycart'] will store products like$_SESSION['mycart'][0],$_SESSION['mycart'][1] will count the prouduct it will be incremented each time a user by anythingthen $_SESSION['mycart'][0],$_SESSION['mycart'][1] will hold data for each product.$_SESSION['mycart'][0]['product_id']=13;$_SESSION['mycart'][0]['productname']='p1';$_SESSION['mycart'][1]['product_id']=3;$_SESSION['mycart'][1]['productname']='p3';as justsomeguy stated above, you have to first format the cart structure of session well at the time when user make a buy, to get the data later well using loops. how you storing it?

Link to comment
Share on other sites

$cartOutput="";$cartTotal="";if(!isset($_SESSION["cart_array"])||count($_SESSION["cart_array"])<1){	$cartOutput="<h2 align='center'>your shopping cart is empty</h2>";}else{	$i=0;	foreach($_SESSION["cart_array"]as $each_item){		$item_id=$each_item['item_id'];		$sql=mysql_query("SELECT productid,productname,price,image FROM products WHERE productid='$item_id' LIMIT 1");		while($row= mysql_fetch_array($sql)){			$productname=$row['productname'];			$price=$row['price'];			$image=$row['image'];			$productid=$row['productid'];		}		$pricetotal=number_format($price*$each_item['quantity'],2,".","");		$cartTotal=number_format($pricetotal+$cartTotal,2,".","");				$cartOutput.="<tr>";		$cartOutput.='<td><img src="images/site pic 2/mysql/'.$image.'" width="45" height="45" /></td>';		$cartOutput.='<td>'. $productid.'</td>';		$cartOutput.='<td>'. $productname.'</td>';		$cartOutput.='<td>$'. $price.'</td>';		$cartOutput.='<td><form action="mycart.php" method="post">		<input name="quantity" type="text" value="'. $each_item['quantity'].'" size="1" maxlength="2" />		<input name="adjustBtn'.$item_id.'" type="submit" value="change" />		<input name="item_to_adjust" type="hidden" value="'.$item_id.'" />		</form></td>';		//$cartOutput.='<td>'. $each_item['quantity'].'</td>';		$cartOutput.='<td>$'. $pricetotal.'</td>';		$cartOutput.='<td><form action="mycart.php" method="post">		<input name="deleteBtn'.$item_id.'" type="submit" value="X" />		<input name="index_to_remove" type="hidden" value="'.$i.'" />		</form>		</td>';		$cartOutput.='</tr>';		$i++;			}		$cartTotal="$".$cartTotal."";}

my cart look like this

Link to comment
Share on other sites

Ok i have managed to insert into the table equal products like products the user chose, but though my data is not all correct i working on it know if u have any suggestions tnx!!

 foreach ($_SESSION['cart_array'] as $value)   {$sql2="INSERT INTO orders(unitprice,pricetotal,quantity,productid,username ) VALUES('$price','$pricetotal','$quantity','$productid','$MM_Username')";if (!mysql_query($sql2,$con))   {   die('Error: ' . mysql_error());   }    }

Link to comment
Share on other sites

Ok i am getting the right number of insert records.The correct product ids.But i get equal price,quantity and pricetotal for all.thats my current code

foreach($_SESSION["cart_array"]as $each_item){		$item_id=$each_item['item_id'];$sql2="INSERT INTO orders(unitprice,pricetotal,quantity,productid,username ) VALUES('$price','$pricetotal','$quantity','$item_id','$MM_Username')";if (!mysql_query($sql2,$con))   {   die('Error: ' . mysql_error());   }    }

I have to go i have a lesson for some hours hope for some suggestion when i come back!

Link to comment
Share on other sites

  foreach($_SESSION["cart_array"]as $each_item){		$item_id=$each_item['quantity'];		$item_id2=$each_item['item_id'];$sql2="INSERT INTO orders(unitprice,pricetotal,quantity,productid,username ) VALUES(' ',' ','$item_id','$item_id2','$MM_Username')";if (!mysql_query($sql2,$con))   {   die('Error: ' . mysql_error());   }    }

All work nice atm.Only price and pricetotal left to finish, i cant figure out how to do that. Using $pricetotal=$_SESSION['pricetotal'] ;Displayes the same value to all.I have posted my cart page some post above.

Link to comment
Share on other sites

You should be saving everything in $_SESSION['cart_array'] and getting it from there, everything about every product needs to be in that array. Obviously $_SESSION['pricetotal'] is only a single value, it's not going to change for each product. Save it in the array.

Link to comment
Share on other sites

I am trying add price and pricetotal into cart_array but probably i dont think i can succed it.i tried to add something like this into the following code but it gets wrong "price"=> 0.00,"pricetotal"=> 0.00As i understand the part of my cart.php which store the values into array is this if i am not wrong.

if(isset($_POST['pid'])){	$pid=$_POST['pid'];	$wasFound=false;	$i=0;	if(!isset($_SESSION["cart_array"])||count($_SESSION["cart_array"])<1){		$_SESSION["cart_array"]=array(0=>array("item_id"=>$pid,"quantity"=>1,));	}else{		foreach ($_SESSION["cart_array"]as $each_item){			$i++;			while(list($key,$value)=each($each_item)){				if($key=="item_id" && $value==$pid){	array_splice($_SESSION["cart_array"],$i-1,1,array(array("item_id"=>$pid,"quantity"=>$each_item['quantity']+1)));					$wasFound=true;				}			}		}		if($wasFound==false){			array_push($_SESSION["cart_array"],array("item_id"=>$pid,"quantity"=>1));			}	}    header("location:mycart.php");	exit();}

Link to comment
Share on other sites

This is where it adds a product if the cart is empty:$_SESSION["cart_array"]=array(0=>array("item_id"=>$pid,"quantity"=>1,));There's a comma at the end that shouldn't be there though. This line adds a new product if the cart is not empty:array_push($_SESSION["cart_array"],array("item_id"=>$pid,"quantity"=>1));As you can see, only the ID and quantity are in the array.

Link to comment
Share on other sites

Yes i forgot the comma, i tried something like this in order to add price and pricetotal but it doesnt work$_SESSION["cart_array"]=array(0=>array("item_id"=>$pid,"quantity"=>1,"price"=> 0.00,"pricetotal"=> 0.00));Here is my whole page if u want to see

<?phpif(isset($_POST['pid'])){	$pid=$_POST['pid'];	$wasFound=false;	$i=0;	if(!isset($_SESSION["cart_array"])||count($_SESSION["cart_array"])<1){		$_SESSION["cart_array"]=array(0=>array("item_id"=>$pid,"quantity"=>1));	}else{		foreach ($_SESSION["cart_array"]as $each_item){			$i++;			while(list($key,$value)=each($each_item)){				if($key=="item_id" && $value==$pid){	array_splice($_SESSION["cart_array"],$i-1,1,array(array("item_id"=>$pid,"quantity"=>$each_item['quantity']+1)));					$wasFound=true;				}			}		}		if($wasFound==false){			array_push($_SESSION["cart_array"],array("item_id"=>$pid,"quantity"=>1));			}	}    header("location:mycart.php");	exit();}?><?phpif(isset($_GET['cmd']) && $_GET['cmd']=="emptycart"){	unset($_SESSION["cart_array"]);}?><?phpif(isset($_POST['item_to_adjust']) && $_POST['item_to_adjust']!=""){	$item_to_adjust=$_POST['item_to_adjust'];	$quantity=$_POST['quantity'];	$quantity=preg_replace('#[^0-9]#i','',$quantity);	if($quantity>=100){$quantity=99;}	if($quantity<1){$quantity=1;}	if($quantity==""){$quantity=1;}	$i=0;	foreach ($_SESSION["cart_array"]as $each_item){			$i++;			while(list($key,$value)=each($each_item)){				if($key=="item_id" && $value==$item_to_adjust){	array_splice($_SESSION["cart_array"],$i-1,1,array(array("item_id"=>$item_to_adjust,"quantity"=>$quantity)));				}			}		}header("location:mycart.php");exit();}?><?phpif(isset($_POST['index_to_remove'])&& $_POST['index_to_remove']!=""){	$key_to_remove=$_POST['index_to_remove'];	if(count($_SESSION["cart_array"])<=1){		unset($_SESSION["cart_array"]);	}else{		unset($_SESSION["cart_array"]["$key_to_remove"]);		sort($_SESSION["cart_array"]);	}}?><?php$cartOutput="";$cartTotal="";if(!isset($_SESSION["cart_array"])||count($_SESSION["cart_array"])<1){	$cartOutput="<h2 align='center'>your shopping cart is empty</h2>";}else{	$i=0;	foreach($_SESSION["cart_array"]as $each_item){		$item_id=$each_item['item_id'];		$sql=mysql_query("SELECT productid,productname,price,image FROM products WHERE productid='$item_id' LIMIT 1");		while($row= mysql_fetch_array($sql)){			$productname=$row['productname'];			$price=$row['price'];			$image=$row['image'];			$productid=$row['productid'];		}		$pricetotal=number_format($price*$each_item['quantity'],2,".","");		$cartTotal=number_format($pricetotal+$cartTotal,2,".","");				$cartOutput.="<tr>";		$cartOutput.='<td><img src="images/site pic 2/mysql/'.$image.'" width="45" height="45" /></td>';		$cartOutput.='<td>'. $productid.'</td>';		$cartOutput.='<td>'. $productname.'</td>';		$cartOutput.='<td>$'. $price.'</td>';		$cartOutput.='<td><form action="mycart.php" method="post">		<input name="quantity" type="text" value="'. $each_item['quantity'].'" size="1" maxlength="2" />		<input name="adjustBtn'.$item_id.'" type="submit" value="change" />		<input name="item_to_adjust" type="hidden" value="'.$item_id.'" />		</form></td>';		//$cartOutput.='<td>'. $each_item['quantity'].'</td>';		$cartOutput.='<td>$'. $pricetotal.'</td>';		$cartOutput.='<td><form action="mycart.php" method="post">		<input name="deleteBtn'.$item_id.'" type="submit" value="X" />		<input name="index_to_remove" type="hidden" value="'.$i.'" />		</form>		</td>';		$cartOutput.='</tr>';		$i++;			}		$cartTotal="$".$cartTotal."";	}$_SESSION['pricetotal']=$pricetotal;$_SESSION['cartTotal']=$cartTotal;?>

Link to comment
Share on other sites

I tried all posible combination but still it doesnt set the values as defined.firstly my insert page i thing is correct

 foreach($_SESSION["cart_array"]as $each_item){		$item_id=$each_item['quantity'];		$item_id2=$each_item['item_id'];		$item_id3=$each_item['price'];		$item_id4=$each_item['pricetotal'];$sql2="INSERT INTO orders(unitprice,pricetotal,quantity,productid,username ) VALUES('$item_id3','$item_id4','$item_id','$item_id2','$MM_Username')";if (!mysql_query($sql2,$con))   {   die('Error: ' . mysql_error());   }    }

I made a lot of combination on cart page but no progressThats my current changes made

	$_SESSION["cart_array"]=array(0=>array("item_id"=>$pid,"quantity"=>1,"price"=> 0,"pricetotal"=> 0));array_splice($_SESSION["cart_array"],$i-1,1,array(array("item_id"=>$pid,"quantity"=>$each_item['quantity']+1,"price"=> 0,"pricetotal"=> 0)));array_push($_SESSION["cart_array"],array("item_id"=>$pid,"quantity"=>1,"price"=> 0,"pricetotal"=> 0));array_splice($_SESSION["cart_array"],$i-1,1,array(array("item_id"=>$item_to_adjust,"quantity"=>$quantity,"price"=>$price,"pricetotal"=>$pricetotal)));

Link to comment
Share on other sites

You're always setting the prices to 0. I'm not sure if that's what you're trying to do or not, but that's what you're doing. So it will get 0 for those when you insert them. So it is working, because it's using the values you're telling it to use. If you want it to use something other than 0 for the prices then you need to figure out where the prices are. The first array_splice line happens when they are updating the quantity for the product, and the second array_splice line is when they're changing something else about the product. If they change the quantity you'll probably need to update the total price to match.

Link to comment
Share on other sites

My cart atm works perfect and displays the right productid/price/pricetotal/quantity ets.Atm i am trying to find a way to enter the price/pricetotal displayed vaues for each product into the table. Some posts above i have posted my whole cart page------------------------------I tried to send the price values through a hidden field to the card$price=$_POST['price'];$_SESSION["cart_array"]=array(0=>array("item_id"=>$pid,"quantity"=>1,"price"=>$price));But still doesnt work. I am thinking for forgeting save the price-pricetotal to the table and just create a view using the productid and joining tables

Link to comment
Share on other sites

What data is coming through in the session? What "doesn't work"? Do the values not show up? Are they wrong? What exactly is not working? All you have to do is save the values in one place, and get them in the other, it's no more complicated than that.

Link to comment
Share on other sites

when i run my insert page it writes that price is still an undifined variable i posted what i did above, i dont really know what else to try-----------Anyway tnx for your help guys i created a view atm from different tables because i need to give the project soon

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...