Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' in

Hi everyone. i am building an ecommerce website where customers orders are been inserted to the database. initial i used mysqli and it worked perfectly but when i use PDO it seems not to work again showing me this error message ‘Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[HY093]: Invalid parameter number: parameter was not defined’ in’. please can someone help me figure this out it is really breaking me here… below is my code, PLEASE HELP ME

cartAction.php

<?php
// initialize shopping cart class
require_once 'class.user.php';
include 'Cart.php';
$cart = new Cart;


// include database configuration file
require_once 'connect.php';
if(isset($_REQUEST['action']) && !empty($_REQUEST['action'])){
    if($_REQUEST['action'] == 'addToCart' && !empty($_REQUEST['id'])){
        $productID = $_REQUEST['id'];
	

             $sql = "SELECT * FROM products WHERE id =:productID";
             $stmt=$db->prepare($sql);
			 $data= array(":productID"=>$productID);
			 $stmt->execute($data);
			 $result=$stmt->setFetchMode(PDO::FETCH_ASSOC);
										
			while($row=$stmt->fetch()){
        $itemData = array(
               'id' => $row['id'],
             'name' => $row['name'],
			'type' => $row['type'],
            'price' => $row['price'],
              'qty' => 1
        );
		
	}
        
        $insertItem = $cart->insert($itemData);
        $redirectLoc = $insertItem?'viewCart.php':'products.php';
        header("Location: ".$redirectLoc);
		
		
    }elseif($_REQUEST['action'] == 'updateCartItem' && !empty($_REQUEST['id'])){
        $itemData = array(
            'rowid' => $_REQUEST['id'],
            'qty' => $_REQUEST['qty']
        );
        $updateItem = $cart->update($itemData);
        echo $updateItem?'ok':'err';die;
		
		
    }elseif($_REQUEST['action'] == 'removeCartItem' && !empty($_REQUEST['id'])){
        $deleteItem = $cart->remove($_REQUEST['id']);
        header("Location: viewCart.php");
	
		
	}elseif($_REQUEST['action'] == 'placeOrder' && $cart->total_items() > 0 && !empty($_SESSION['userSession'])){
		
        // insert order details into database
		$query= 'INSERT INTO orders (customer_id, total_price, created, modified) VALUES (:customer_id, :total_price, :date, :date)';
        $insertOrder = $db->prepare($query);
		//$insertOrder->bindparam(":invoice", $finalcode, PDO::PARAM_INT);
		$insertOrder->bindparam(":customer_id", $_SESSION['userSession'], PDO::PARAM_INT);
		$insertOrder->bindparam(":total_price", $cart->total(), PDO::PARAM_INT);
		$insertOrder->bindparam(":date", date('Y-m-d H:i:s'), PDO::PARAM_INT);
		$insertOrder->bindparam(":date", date('Y-m-d H:i:s'), PDO::PARAM_INT);
		$insertOrder->execute();
		
		
		
           if($insertOrder){
           $orderID =$db->lastInsertId;
           // $sql = '';
            // get cart items
            $cartItems = $cart->contents();
            foreach($cartItems as $item){
                $query = 'INSERT INTO order_items (order_id, product_id, quantity) VALUES (:orderID, :product_id,:quantity)';
				
		$insertOrderItems = $db->prepare($query);
		$insertOrderItems->bindparam(":order_id", $orderID, PDO::PARAM_INT);
		$insertOrderItems->bindparam(":product_id", $item['id'], PDO::PARAM_INT);
		$insertOrderItems->bindparam(":quantity", $item['qty'], PDO::PARAM_INT);
		$insertOrderItems->execute();
            }
            // insert order items into database
           // $insertOrderItems = $db->multi_query($sql);
            
            if($insertOrderItems){
                $cart->destroy();
                header("Location: orderSuccess.php?id=$orderID");
            }else{
                header("Location: checkout.php");
            }
        }else{
            header("Location: checkout.php");
        }
    }else{
        header("Location: index.php");
    }
}else{
    header("Location: index.php");
}
?>

Cart.php

<?php 

session_start();
class Cart {
    protected $cart_contents = array();
    
    public function __construct(){
        // get the shopping cart array from the session
        $this->cart_contents = !empty($_SESSION['cart_contents'])?$_SESSION['cart_contents']:NULL;
		if ($this->cart_contents === NULL){
			// set some base values
			$this->cart_contents = array('cart_total' => 0, 'total_items' => 0);
		}
    }
    
    /**
	 * Cart Contents: Returns the entire cart array
	 * @param	bool
	 * @return	array
	 */
	public function contents(){
		// rearrange the newest first
		$cart = array_reverse($this->cart_contents);

		// remove these so they don't create a problem when showing the cart table
		unset($cart['total_items']);
		unset($cart['cart_total']);

		return $cart;
	}
    
    /**
	 * Get cart item: Returns a specific cart item details
	 * @param	string	$row_id
	 * @return	array
	 */
	public function get_item($row_id){
		return (in_array($row_id, array('total_items', 'cart_total'), TRUE) OR ! isset($this->cart_contents[$row_id]))
			? FALSE
			: $this->cart_contents[$row_id];
	}
    
    /**
	 * Total Items: Returns the total item count
	 * @return	int
	 */
	public function total_items(){
		return $this->cart_contents['total_items'];
	}
    
    /**
	 * Cart Total: Returns the total price
	 * @return	int
	 */
	public function total(){
		return $this->cart_contents['cart_total'];
	}
    
    /**
	 * Insert items into the cart and save it to the session
	 * @param	array
	 * @return	bool
	 */
	public function insert($item = array()){
		if(!is_array($item) OR count($item) === 0){
			return FALSE;
		}else{
            if(!isset($item['id'], $item['name'], $item['price'], $item['qty'])){
                return FALSE;
            }else{
                /*
                 * Insert Item
                 */
                // prep the quantity
                $item['qty'] = (float) $item['qty'];
                if($item['qty'] == 0){
                    return FALSE;
                }
                // prep the price
                $item['price'] = (float) $item['price'];
                // create a unique identifier for the item being inserted into the cart
                $rowid = md5($item['id']);
                // get quantity if it's already there and add it on
                $old_qty = isset($this->cart_contents[$rowid]['qty']) ? (int) $this->cart_contents[$rowid]['qty'] : 0;
                // re-create the entry with unique identifier and updated quantity
                $item['rowid'] = $rowid;
                $item['qty'] += $old_qty;
                $this->cart_contents[$rowid] = $item;
                
                // save Cart Item
                if($this->save_cart()){
                    return isset($rowid) ? $rowid : TRUE;
                }else{
                    return FALSE;
                }
            }
        }
	}
    
    /**
	 * Update the cart
	 * @param	array
	 * @return	bool
	 */
	public function update($item = array()){
		if (!is_array($item) OR count($item) === 0){
			return FALSE;
		}else{
			if (!isset($item['rowid'], $this->cart_contents[$item['rowid']])){
				return FALSE;
			}else{
				// prep the quantity
				if(isset($item['qty'])){
					$item['qty'] = (float) $item['qty'];
					// remove the item from the cart, if quantity is zero
					if ($item['qty'] == 0){
						unset($this->cart_contents[$item['rowid']]);
						return TRUE;
					}
				}
				
				// find updatable keys
				$keys = array_intersect(array_keys($this->cart_contents[$item['rowid']]), array_keys($item));
				// prep the price
				if(isset($item['price'])){
					$item['price'] = (float) $item['price'];
				}
				// product id & name shouldn't be changed
				foreach(array_diff($keys, array('id', 'name')) as $key){
					$this->cart_contents[$item['rowid']][$key] = $item[$key];
				}
				// save cart data
				$this->save_cart();
				return TRUE;
			}
		}
	}
   
    /**
	 * Save the cart array to the session
	 * @return	bool
	 */
	protected function save_cart(){
		$this->cart_contents['total_items'] = $this->cart_contents['cart_total'] = 0;
		foreach ($this->cart_contents as $key => $val){
			// make sure the array contains the proper indexes
			if(!is_array($val) OR !isset($val['price'], $val['qty'])){
				continue;
			}
	 
			$this->cart_contents['cart_total'] += ($val['price'] * $val['qty']);
			$this->cart_contents['total_items'] += $val['qty'];
			$this->cart_contents[$key]['subtotal'] = ($this->cart_contents[$key]['price'] * $this->cart_contents[$key]['qty']);
		}
		
		// if cart empty, delete it from the session
		if(count($this->cart_contents) <= 2){
			unset($_SESSION['cart_contents']);
			return FALSE;
		}else{
			$_SESSION['cart_contents'] = $this->cart_contents;
			return TRUE;
		}
    }
    
    /**
	 * Remove Item: Removes an item from the cart
	 * @param	int
	 * @return	bool
	 */
	 public function remove($row_id){
		// unset & save
		unset($this->cart_contents[$row_id]);
		$this->save_cart();
		return TRUE;
	 }
     
    /**
	 * Destroy the cart: Empties the cart and destroy the session
	 * @return	void
	 */
	public function destroy(){
		$this->cart_contents = array('cart_total' => 0, 'total_items' => 0);
		unset($_SESSION['cart_contents']);
	}
}

function createRandomPassword() {
	$chars = "183232393232523232023456789";
	srand((double)microtime()*1000000);
	$i = 0;
	$pass = '' ;
	while ($i <= 7) {

		$num = rand() % 33;

		$tmp = substr($chars, $num, 1);

		$pass = $pass . $tmp;

		$i++;

	}
	return $pass;
}
$finalcode='RS-'.createRandomPassword();
?>

connect.php

<?php
/* Database config */
$db_host		= 'localhost';
$db_user		= 'root';
$db_pass		= '';
$db_database	= ''; 

/* End config */

$db = new PDO('mysql:host='.$db_host.';dbname='.$db_database, $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

?>

Which line gives you the error?

@DarthGuido the lie which gives me error is as follows

if($insertOrder){
           $orderID =$db->lastInsertId;
           // $sql = '';
            // get cart items
            $cartItems = $cart->contents();
            foreach($cartItems as $item){
                $query = 'INSERT INTO order_items (order_id, product_id, quantity) VALUES (:orderID, :product_id,:quantity)';
				
		$insertOrderItems = $db->prepare($query);
		$insertOrderItems->bindparam(":order_id", $orderID, PDO::PARAM_INT);
		$insertOrderItems->bindparam(":product_id", $item['id'], PDO::PARAM_INT);
		$insertOrderItems->bindparam(":quantity", $item['qty'], PDO::PARAM_INT);
		$insertOrderItems->execute();

thanks all for the help… i have got it working perfectly now… was just a silly mistake on my part
should be
$orderID =$db->lastInsertId();
not
$orderID =$db->lastInsertId;

and also
this should be
$insertOrderItems->bindparam(“:orderID”, $orderID, PDO::PARAM_INT);

and not
$insertOrderItems->bindparam(“:order_id”, $orderID, PDO::PARAM_INT);

thanks anyways for those who try helping me solve this problem

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.