Jump to content

Illegal Offset Type - Array


abbos

Recommended Posts

Hi,

 

I'm fairly new to PHP so forgive any silly mistakes in my code.

 

I have the following code:

 

$product_id = $_POST['id'];
		$qty = $_POST['qty'];
		$_SESSION['cart'][$product_id] = $qty;

 

Which works fine. My problem starts when I update the quantity of the item, as it re-submits the page and $product_id then turns into an array. As a result this is what is causing me to then receive an Illegal Offset Error on the page.

 

I've tried to re-write the code but I'm not having much luck.

 

Any help would be appriciated.

 

Thanks,

Abbos

 

EDIT: I forgot to mention that this problem has only started since I upgraded from PHP 4.4.7 to 5.2.6

Link to comment
https://forums.phpfreaks.com/topic/132114-illegal-offset-type-array/
Share on other sites

Ok,

 

Here is the complete page:

 

<? session_start(); ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<?
include("db/dbconnect.inc");
$counter = 0;

// if there is a product_id and that product_id doesn't exist in the database then display an error message
if($product_id && !productExists($product_id )) 
{
	die("Error. Product Doesn't Exist");
    }
else
{
	if($cartQty) 
	{
		$product_id = $_POST['id'];		// if there is a qty then post that item using its ID  	    
		for($i=0; $i < count($cartQty); $i++) 
		{
			if($cartQty[$i] != 0) 
			{
				$_SESSION['cart'][$product_id[$i]] = $cartQty[$i]; 
			}
			else
			{
				unset($_SESSION['cart']); 
			}
		}
	}
	else
	{
		$product_id = $_POST['id'];
		$qty = $_POST['qty'];
		$_SESSION['cart'][$product_id] = $qty;		// add one to qty of product with ID $product_id 
	}
     }
?>

<html>
<head><title>Cart</title>

<!--validation-->
<script type="text/javascript">
function validate_required(field,alerttxt) {
with (field) {
	if (value==null||value==""){
		alert(alerttxt);
		return false;
	}
	else {
		return true;
	}
}
}

function validate_form(thisform) {
with (thisform) {
	if (validate_required(quoteref,"A Quote Reference must be filled out!")==false) {
		quoteref.focus();
		return false;
	}
}
}
</script>

<!--add labour to total-->
<script type="text/javascript">
var oldTotal=0;
function showlabour(total,labour) {
//alert(total);
if(document.getElementById('labour').checked == true) {
	total = parseFloat(total) + labour;
	oldTotal = total;
	total = formatNumber(total,'2',',','.','','','','');
	document.getElementById('total').innerHTML = '<b>£'+total+'</b>';
	document.getElementById('newTotal').value = total;
	//location.href="summary.php?newTotal=" + total;
	alert(total);

}else {
	total = parseFloat(oldTotal) - labour;
	oldTotal = total;
	total = formatNumber(total,'2',',','.','','','','');
	document.getElementById('total').innerHTML = '<b>£'+total+'</b>';
	//document.getElementById('newTotal').value = total;
	//location.href="summary.php?total=" + total;
}
}

function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) {
var x = Math.round(num * Math.pow(10,dec));
if (x >= 0) 
n1=n2='';
var y = (''+Math.abs(x)).split('');
var z = y.length - dec; 
if (z<0) 
z--; 
for(var i = z; i < 0; i++) 
y.unshift('0');
y.splice(z, 0, pnt); 
if(y[0] == pnt) 
y.unshift('0'); 
while (z > 3) 
{
	z-=3; 
	y.splice(z,0,thou);
}
var r = curr1+n1+y.join('')+n2+curr2;
return r;
}
</script>

<!--submit update/summary form to their different locations-->
<script language="Javascript"> 
function OnButton1() { 
    document.form1.action = "estimate.php" 
    document.form1.submit();	// submit the page 
    return true; 
} 

function OnButton2() { 
document.form1.action = 'summary.php';
    document.form1.submit = 'function validate_form(this)';
    return true; 
}
</script>

<? include("design/menu.inc"); ?>
</head>

<body>

<? include("design/header.php"); ?>

<div class="itembox">
<div class="boxtitle"><a href="index.php">Home</a> > Estimate</div>

<form name="form1" method="POST">
<?		

// if cart isn't empty show cart
if($_SESSION['cart']) { 

echo 'Customer Ref:<input type="text" name="ref" /><br/><br/>';   
echo '<table border="0" width="100%">';
echo '<tr class="estimatetitle">';
echo '<td colspan="2" nowrap>Item</td>';
echo '<td colspan="1" width="100px">Quantity</td>';
echo '<td colspan="1" width="100px">Cost</td>';
echo '</tr>';
echo '<tr>';
echo '<td colspan="4"><hr size="2"></td>';
echo '</tr>';

// iterate through cart, the $product_id is the key and $quantity is the value
    foreach($_SESSION['cart'] as $product_id => $quantity) {
    			        
       	$sql = sprintf("SELECT title, salesprice, photo FROM product WHERE id = %d", $product_id); 
	//return mysql_num_rows(mysql_query($sql)) > 0;

	$result = mysql_query($sql);

	// display row if product exists
	$counter = $counter + 1;

	if($result > 0) { 
            list($title, $salesprice, $photo) = mysql_fetch_row($result);
		$line_cost = $salesprice * $quantity;			// work out line cost
		$totallinecost = $totallinecost + $line_cost;	// add to total cost	
		$totalLabour = $labour * $quantity;
		$totalLabourCost = $labour * $quantity + $totalLabourCost;
		$total = $totallinecost + $delivery;	
		$totallabourcost =  $totallabourcost + $totalLabour; 
		$jstotal = $totlab + $total;

/*			setlocale(LC_MONETARY, 'en_GB');
		$jstotal = number_format('%i', $total);		
		$jstotal = explode('GBP',$total);			
		$jstotal = $total[1];	

		$totalCost = number_format('%i', $totalCost);		
		$totalCost = explode('GBP',$totalCost);
		$totalCost = $totalCost[1];	 

            $totlab = number_format('%i', $totlab);		
		$totlab = explode('GBP',$totlab);	
		$totlab = $totlab[1];

		$delivery = number_format('%i', $delivery);		
		$delivery = explode('GBP',$delivery);	
		$delivery = $delivery[1];

		$line_cost = number_format('%i', $line_cost);		
		$line_cost = explode('GBP',$line_cost);	
		$line_cost = $line_cost[1];
*/

		// display item info in a table 
		echo '<tr>';
		echo '<td class="photo"><img src="images/', $photo, '"border="1" width="50px" height="50px" /></td>';
		echo '<td class="estimatedesc">', $title, '<input name="item[', $counter, '][title]" type="hidden" value="', $title, '" />';
		echo '<table class="estimatedesc">';
		echo '<tr>';
		echo '</tr>';
		echo '</table>';
		echo '</td>';
		echo '<td class="estimateqty"><input name="cartQty[]" type="text" value="', $quantity, '" maxlength="4" size="4" />*<input name="item[', $counter, '][cartQty]" type="hidden" value="', $quantity, '" /></td>';

		echo '<td class="estimatecost">£', $line_cost, '<input name="item[', $counter, '][line_cost]" type="hidden" value="', $line_cost, '" /></td>';
            echo '</tr>';
		echo '<input name="id[]" type="hidden" value=', $product_id, ' />'; // ID is needed to update qty
	}
}

	// grey line 3 (after items)
echo '<tr>';
echo '<td colspan="4"><hr size="1"></td>';
echo '</tr>';

// labour
    echo '<tr>';
echo "<td colspan='2'></td>"; 
echo '<td class="estimateprices">Labour</td>';
    echo '<td class="estimateprices">£', '<input name="totlab" type="text" value="', $totlab, '" maxlength="5" size="7" /></td>';
    echo '</tr>';

// delivery
    echo '<tr>';
echo '<td colspan="2"></td>';	//empty cell
    echo '<td class="estimateprices">Delivery</td>';
    echo '<td class="estimateprices">£', '<input name="delivery" type="text" value="', $delivery, '" maxlength="5" size="7" /></td>';echo '</tr>';

// total
    echo '<tr>';
echo '<td colspan="2"><b>*set quantity to zero to remove item</b></td>';
    echo '<td class="estimatetitle">Total</td>';
    echo '<td class="estimatetitle"><div id="total">£', $jstotal, '<input id="newTotal" name="newTotal" type="hidden" value="', $jstotal, '" /><input name="total" type="hidden" value="', $jstotal, '" /></div></td>';
echo '</tr>';

// grey line 4 (bottom)
echo '<tr>';
echo '<td colspan="4"><hr size="1"></td>';
    echo '</tr>';

// update/summary buttons
echo '<tr>';
echo '<td colspan="4" align="center">';
echo '<input type="submit" name"button2" value="View Summary" onclick="return OnButton2();" />'; //add id="summary", this allows you to add a design to your button using CSS 
echo '<input type="button" name="button1" value="update" onclick="return OnButton1();" />';	
echo '</td>';
echo '</tr>';
}
else { 
   //otherwise tell the user they have no items to estimate
    echo '<table border="0" align="center">';
    echo '<tr>';
    echo '<td colspan="3" align="center">You have no items selected to be estimated.</td>';
    echo '</tr>';        
    echo '</table>';
} 

// check if a product exists
// use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
function productExists($product_id) {
    $sql = sprintf("SELECT * FROM product WHERE id = %d;", $product_id); 
return mysql_num_rows(mysql_query($sql)) > 0;
}
?>

</table>
</form>

<? include("design/footer.php"); ?>

</body>
</html>

   // if there is a product_id and that product_id doesn't exist in the database then display an error message
   if($product_id && !productExists($product_id ))
   {
      die("Error. Product Doesn't Exist");
    }
   else
   {
      if($cartQty)
      {
         $product_id = $_POST['id'];      // if there is a qty then post that item using its ID        
         for($i=0; $i < count($cartQty); $i++)
         {
            if($cartQty[$i] != 0)
            {
               $_SESSION['cart'][$product_id[$i]] = $cartQty[$i];
            }
            else
            {
               unset($_SESSION['cart']);
            }
         }
      }
      else
      {
         $product_id = $_POST['id'];
         $qty = $_POST['qty'];
         $_SESSION['cart'][$product_id[0]] = $qty;      // add one to qty of product with ID $product_id
      }

 

$_SESSION['cart'][$product_id[0]] = $qty; // already changed, added [0] to the end of $product_id

 

Since you have defined id as an array in the form it will return as an array always, just simply access the first element of it by changing the above line.

Archived

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

×
×
  • 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.