Error insert data into table

Helllo.first of all,i am really noob in programming,i have follow an instruction how to create a shopping cart,i want to make a modification so the shopping cart system can be use as a restaurant system for staff to record customer order,so the system do not need to record the customer details.I have error when i try to insert all the choosen data into table, the error happen in cart.php.

Here is the error:
Notice: Undefined index: name in C:\xampp\htdocs\emakengku\cart.phpon line 7
Notice: Undefined index: quantity inC:\xampp\htdocs\emakengku\cart.php on line 8
Notice: Undefined index: price in C:\xampp\htdocs\emakengku\cart.phpon line 9

Here is the code:
index2.php

<?
session_start();
error_reporting(E_ALL);
require("connection.php");
if(isset($_GET['page'])){

	$pages=array("products", "cart");
	if(in_array($_GET['page'], $pages)) {
	
		$_page=$_GET['page'];
	
	}else{
	
		$_page="products";
	
	}
	
}else{

$_page="products";

}
?>



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>


<body>
</body>
</html>

<link rel="stylesheet" href="style2.css" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>

<script type="text/javascript">
$(function() {

});
</script>
</head>

<body>
<div id="container">

<div id="main">
<?php require($_page.".php");     ?>

</div>

<div id="sidebar">
<h1>Cart</h1>

<?php
if(isset($_SESSION['cart'])){

$sql="SELECT * FROM products WHERE id_product IN (";

foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}
$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$query=mysql_query($sql);
while($row=mysql_fetch_array($query)){

?>
<p><?php echo $row['name'] ?> x <?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?></p>
<?php }

?>

<hr />
<a href="index2.php?page=cart">Go to Cart</a>


<?php





}else{

echo "<p>Your Cart is empty</p>";

}
?>
</div>

</div>
</body>

products.php

<?php

	if(isset($_GET['action']) && $_GET['action']=="add"){
	
		$id=intval($_GET['id']);
		
		if(isset($_SESSION['cart'][$id])){
		
			$_SESSION['cart'][$id]['quantity']++;
		
		}else{
		
			$sql_s="SELECT * FROM products
				WHERE id_product={$id}";
			$query_s=mysql_query($sql_s);
			if(mysql_num_rows($query_s)!=0){
				$row_s=mysql_fetch_array($query_s);
				
					
					
					$_SESSION['cart'][$row_s['id_product']]=array(
							"quantity" => 1,
							"price" => $row_s['price']
							
							);
				
				
				}else{
				
					$message="This product id it's invalid!";
	

		}
		}
		}
		
		


?>


<h1>Product List</h1>
<?php

	if(isset($message)){
	echo "<h2>$message</h2>";
	}
?>
<table>
<tr>
    <th>Name</th>
	<th>Description</th>
	<th>Price</th>
	<th>Action</th>
</tr>
<?php
$sql="SELECT * FROM products ORDER BY name ASC";

$query=mysql_query($sql);

while ($row=mysql_fetch_array($query)) {

?>
<tr>
	<td><?php echo $row['name'] ?></td>
	<td><?php echo $row['description'] ?></td>
	<td>RM <?php echo $row['price'] ?></td>
	<td><a href="index2.php?page=products&action=add&id=<?php echo $row['id_product'] ?>">Add To Cart</a></td>
</tr>
<?php
}
?>

</table>

cart.php

<?php
error_reporting(E_ALL);
 ini_set('display_errors', '1');
require("connection.php");
if(isset($_POST['submit2']))

	$name=$_POST["name"];
	$quantity=$_POST["quantity"];
	$price=$_POST["price"];
 $sql_insert = "INSERT INTO order ('name', 'quantity', 'price')
values ('name', 'quantity', 'price')";
echo "sucess!";



 if(isset($_POST['submit'])){

 foreach($_POST['quantity'] as $key => $val) {
 	if($val==0) {
	unset($_SESSION['cart'][$key]);
	}else{
	$_SESSION['cart'][$key]['quantity']=$val;
	


	}
	}


 }

?>



<a href="index2.php?page=products">Go back to product page</a>
<h1>View Cart</h1>

<form method="post" action"index2.php?page=cart">

<table>
<tr>
	<th>Name</th>
	<th>Quantity</th>
	<th>Price</th>
	<th>Item Price</th>



</tr>
<?php

	$sql="SELECT * FROM products WHERE id_product IN (";

foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}
$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$query=mysql_query($sql);
$totalprice=0;
while($row=mysql_fetch_array($query)){
	$subtotal=$_SESSION['cart'][$row['id_product']]['quantity']*$row['price'];
	$totalprice+=$subtotal;

?>
<tr>
<td><?php echo $row['name'] ?></td>
<td><input type="text" name="quantity[<?php echo $row['id_product'] ?>]" size="5" value="<?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?>"</td>
<td>RM <?php echo $row['price'] ?></td>
<td>RM <?php echo $_SESSION['cart'][$row['id_product']]['quantity']*$row['price'] ?></td>



</tr>



<?php
}

?>
<tr>
<td>Total Price: <?php echo $totalprice  ?></td>


</tr>

</table>
<button type="submit" name="submit"> Update Cart</button>
<button type="submit" name="submit2"> Update Cart</button>


</form>
<br />
<p> To remove an item,set the quantity to 0</p>

Please be aware that the mysql_* extension is now deprecated as of the current version of PHP and will very likely be removed from the next 5.x version and will likely not be in PHP 6.x (when it eventually is released). You should migrate over to either the mysqli_* extension or to PDO. PDO is a better choice as it doesn’t tie you down so much to a particular database server software.

Once you have migrated you should use Prepared Statements to prevent SQL Injection attacks. Have a read of this article from the PHP manual, it shows how to use prepared statements with PDO and also explains the principle.

Yes I would go with PDO and bind all user input. Note on the cart page where you are not using the variables as the VALUES nor are you executing the query.

<?php
$sql_insert = "INSERT INTO order ('name', 'quantity', 'price')
values('$name', '$quantity', '$price')";
mysql_query($sql_insert);
?>

HI thelee,

The reason for the undefined index is that your php code could not see the variable what is set to your html code

example in your cart.php


<td><input type="text" name="quantity[<?php echo $row['id_product'] ?>]" size="5" value="<?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?>"</td>

change it to this


<td><input type="text" name="quantity[]" size="5" value="<?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?>"</td>

I suggest to install firebug so that you can see what is set

http://getfirebug.com/

it echo sucess but no data inserted into table.i am really sorry guys,im still learning.

Did you add Drummin’s code from above? Your code just before the “echo ‘success’;” line creates the sql query, but does not actually execute it, so it won’t have any effect on the database. You had:


   $name=$_POST["name"];
    $quantity=$_POST["quantity"];
    $price=$_POST["price"];
 $sql_insert = "INSERT INTO order ('name', 'quantity', 'price')
values ('name', 'quantity', 'price')";
echo "sucess!";

As you can see, that only creates a variable called $sql_insert then says “success”, it doesn’t do anything with it. As Drummin said above, you need to add


mysql_query($sql_insert);

just after you create $sql_insert, and before you echo “success”. In fact when you learn more you will also need to check that the query has executed properly before you display “success”, but that’s another matter.

And as SpacePhoenix said, you need to look at getting rid of mysql calls and using mysqli or PDO calls instead. It sounds like a lot of work, but once you learn how to change from one to the other it’s not that terrible. It’s important because if you finish this site and host it somewhere, at some point your host will upgrade their server to the latest version of PHP and all your mysql calls will stop working. Then you’ll have to make the changes while you’ve got a customer or user on the phone every couple of minutes asking why their site is still down. So I’d recommend that once you have this part working, as an exercise, work through changing it to PDO and you’ll see how it isn’t really that hard.

hye droopsnoot, thanks for your feedback,i have add the

mysql_query($sql_insert); 

i also got this feedback from someone:
"Your form is broken, you’re missing the name, quantity etc inputs you later try to use in the script ($_POST[‘name’] etc) - in file cart.php.

It’s hard to find it, because the code is huge mess, but I didn’t manage to find any inputs with those names.

Also, besides the obvious flaws like using deprecated mysql_* functions, you really should not mix logic and view this way. Doing database query in the middle of rendering a form is NOT GOOD."

the form in cart.php do not have input,so it wont insert into table ? am i correct?

True, the code does seem to be all over the place. I can see a quantity input that jemz talked about, but other than having two submit buttons that is the only input in your form on cart.php, and it doesn’t seem to have a closing angle brace. For example:


<td><input type="text" name="quantity[<?php echo $row['id_product'] ?>]" size="5" value="<?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?>"</td>
<td>RM <?php echo $row['price'] ?></td>
<td>RM <?php echo $_SESSION['cart'][$row['id_product']]['quantity']*$row['price'] ?></td>

Your query is looking for name and price as well as quantity. I assume ‘name’ is actually some kind of product code (normally you’d put product code in the order table, not the name) and the others need to either be added to the form, or removed from the query.

i have change the code to be like this

&lt;?php
require("connection.php");
if(isset($_POST['submit2'])) {

	$name=$_POST["name"];
	$quantity=$_POST["quantity"];
	$price=$_POST["price"];
$sql_insert = "INSERT INTO `order` (`name`, `quantity`, `price`)
values('$name', '$quantity', '$price')";
mysql_query($sql_insert) or die(mysql_error());

echo "sucess!";

}

 if(isset($_POST['submit'])){

 foreach($_POST['quantity'] as $key =&gt; $val) {
 	if($val==0) {
	unset($_SESSION['cart'][$key]);
	}else{
	$_SESSION['cart'][$key]['quantity']=$val;
	


	}
	}


 }

?&gt;

data is inserted into table,but the data is wrong

actually this system i will use as a restaurant system,so it wont record the product id,because after customer confirm with their order, kitchen department can see what the customer have order.

@thelee; You need to be aware that your code is wide open to SQL injection attack. The golden rule is to never let any user submitted data anywhere near the database without being escaped. That includes anything from the following super-global arrays:

  • $_GET
  • $_POST
  • $_FILES
  • $_COOKIE
  • $_REQUEST

To be absolutely safe you should be using prepared statements.

That SitePoint article explains about migrating from using the old and deprecated mysql_* extension over to using PDO. Also you should impliment some proper error handling, the modern way is the use of exceptions

OK, well it’s not actually inserting the wrong data. Your form-variable “quantity” is coming back as an array, but as you’re feeding it into a single row in your query, the result you have is correct. What you need to do is loop around each element of the quantity variable (and the dish name or id and any other array fields) and insert each one into the database. So you’d want something like:


foreach ($quantity as $q) {
  $query = "insert into orders customer_id, quantity, name values($custid, $q, $name)";
  mysql_query($query);
  }

which would run through each element of the quantity array, get its value in $q, then insert it into your table. (In the example, I’ve used mysql (which you shouldn’t, I can’t remember if anyone has mentioned that) and assumed you already got customer-id and name from somewhere else.)

If you run back a couple of weeks on this forum there’s another question about writing a shopping cart that had a lot of detailed replies and might give you enough information to see what the issues are and how best to add the extra fields that you need. If you’re new to PHP and/or programming of any kind, it’s a reasonably complex thing to pick to start with, and the code you’re adapting isn’t helping.

I’d think you would still want a product id to refer to each dish, perhaps with a ‘note’ field to indicate medium rare, burnt to a crisp, or any other special requirements. The kitchen would still know what dish it is because when you extract the data for them, you’ll convert it back into the proper name. I’m assuming the restaurant is working off a fixed menu rather than just cooking up anything the customer wants, though all this is a bit off-topic really.