Jump to content

Shopping cart - Kinda new to PHP - STUCK!! Please help me out.


jmclocals

Recommended Posts

I'm writing a basic shopping car to query to a user and inventory table in mySQL.  Whenever I go back to my site to test it out, it doesn't echo the cart properly.  Some of this script was taken from an open source free project that I found online.  The tutor who wrotte this script doesn't explain things AT ALL..

 

I think there's a problem with my $array (line 27) in my 'functions.inc' file?  Whatever the case, I cant get the thing to work properly...  Bottom line.

 

On top of that, when I'm finished, I have to write a checkout script to process payments, and I havent a clue where to start with that.

 

Heres my source...  Can someone help me out if you have some time to spare?  Thanks a bunch.

 

<<<<<<<CART.PHP>>>>>>>

 

<?php

// Include MySQL class

require_once('inc/mysql.class.php');

// Include database connection

require_once('inc/global.inc.php');

// Include functions

require_once('inc/functions.inc.php');

// Start the session

session_start();

// Process actions

$cart = $_SESSION['cart'];

$action = $_GET['action'];

switch ($action) {

  case 'add':

      if ($cart) {

        $cart .= ','.$_GET['id'];

      } else {

        $cart = $_GET['id'];

      }

      break;

  case 'delete':

      if ($cart) {

        $items = explode(',',$cart);

        $newcart = '';

        foreach ($items as $item) {

            if ($_GET['id'] != $item) {

              if ($newcart != '') {

                  $newcart .= ','.$item;

              } else {

                  $newcart = $item;

              }

            }

        }

        $cart = $newcart;

      }

      break;

  case 'update':

  if ($cart) {

      $newcart = '';

      foreach ($_POST as $key=>$value) {

        if (stristr($key,'qty')) {

            $id = str_replace('qty','',$key);

            $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);

            $newcart = '';

            foreach ($items as $item) {

              if ($id != $item) {

                  if ($newcart != '') {

                    $newcart .= ','.$item;

                  } else {

                    $newcart = $item;

                  }

              }

            }

            for ($i=1;$i<=$value;$i++) {

              if ($newcart != '') {

                  $newcart .= ','.$id;

              } else {

                  $newcart = $id;

              }

            }

        }

      }

  }

  $cart = $newcart;

  break;

}

$_SESSION['cart'] = $cart;

?>

 

 

<<<<<<<<<MYSQL.CLASS.PHP>>>>>>>>>>>

 

 

?php

/**

* MySQL Database Connection Class

* @access public

* @package SPLIB

*/

class MySQL {

    /**

    * MySQL server hostname

    * @access private

    * @var string

    */

    var $host;

 

    /**

    * MySQL username

    * @access private

    * @var string

    */

    var $user;

 

    /**

    * MySQL user's password

    * @access private

    * @var string

    */

    var $pass;

 

    /**

    * Name of database to use

    * @access private

    * @var string

    */

    var $name;

 

    /**

    * MySQL Resource link identifier stored here

    * @access private

    * @var string

    */

    var $dbConn;

 

    /**

    * Stores error messages for connection errors

    * @access private

    * @var string

    */

    var $connectError;

 

    /**

    * MySQL constructor

    * @param string host (MySQL server hostname)

    * @param string dbUser (MySQL User Name)

    * @param string dbPass (MySQL User Password)

    * @param string dbName (Database to select)

    * @access public

    */

    function MySQL ($host,$user,$pass,$name) {

        $this->host=$host;

        $this->user=$user;

        $this->pass=$pass;

        $this->name=$name;

        $this->connectToDb();

    }

 

    /**

    * Establishes connection to MySQL and selects a database

    * @return void

    * @access private

    */

    function connectToDb () {

        // Make connection to MySQL server

        if (!$this->dbConn = @mysql_connect($this->host,

                                      $this->user,

                                      $this->pass)) {

            trigger_error('Could not connect to server');

            $this->connectError=true;

        // Select database

        } else if ( !@mysql_select_db($this->name,$this->dbConn) ) {

            trigger_error('Could not select database');

            $this->connectError=true;

        }

    }

 

    /**

    * Checks for MySQL errors

    * @return boolean

    * @access public

    */

    function isError () {

        if ( $this->connectError )

            return true;

        $error=mysql_error ($this->dbConn);

        if ( empty ($error) )

            return false;

        else

            return true;

    }

 

    /**

    * Returns an instance of MySQLResult to fetch rows with

    * @param $sql string the database query to run

    * @return MySQLResult

    * @access public

    */

 

}

 

/**

* MySQLResult Data Fetching Class

* @access public

* @package SPLIB

*/

class MySQLResult {

    /**

    * Instance of MySQL providing database connection

    * @access private

    * @var MySQL

    */

    var $mysql;

 

    /**

    * Query resource

    * @access private

    * @var resource

    */

    var $query;

 

    /**

    * MySQLResult constructor

    * @param object mysql  (instance of MySQL class)

    * @param resource query (MySQL query resource)

    * @access public

    */

    function MySQLResult(& $mysql,$query) {

        $this->mysql=& $mysql;

        $this->query=$query;

    }

 

    /**

    * Fetches a row from the result

    * @return array

    * @access public

    */

    function fetch () {

        if ( $row=mysql_fetch_array($this->query,MYSQL_ASSOC) ) {

            return $row;

        } else if ( $this->size() > 0 ) {

            mysql_data_seek($this->query,0);

            return false;

        } else {

            return false;

        }

    }

 

    /**

    * Returns the number of rows selected

    * @return int

    * @access public

    */

    function size () {

        return mysql_num_rows($this->query);

    }

 

    /**

    * Returns the ID of the last row inserted

    * @return int

    * @access public

    */

    function insertID () {

        return mysql_insert_id($this->mysql->dbConn);

    }

 

    /**

    * Checks for MySQL errors

    * @return boolean

    * @access public

    */

    function isError () {

        return $this->mysql->isError();

    }

}

?>

 

 

<<<<<<<<<<<<global.inc.php>>>>>>>>>>>>>>

 

 

 

<?php

$host = 'MY LOCALHOST';

$user = 'calgrp1';

$pass = 'MY PASSWORD';

$name = 'MY DB NAME';

$db = &new MySQL($host,$user,$pass,$name);

?>

 

 

 

<<<<<<<<<<<<functions.php>>>>>>>>>>>

 

 

 

<?php

function writeShoppingCart() {

  $cart = $_SESSION['cart'];

  if (!$cart) {

      return '<p>You have no items in your shopping cart</p>';

  } else {

      // Parse the cart session variable

      $items = explode(',',$cart);

      $s = (count($items) > 1) ? 's':'';

      return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart[/url]</p>';

  }

}

 

function showCart() {

  global $db;

  $cart = $_SESSION['cart'];

  if ($cart) {

      $items = explode(',',$cart);

      $contents = array();

      foreach ($items as $item) {

        $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;

      }

      $output[] = '<form action="cart.php?action=update" method="post" id="cart">';

      $output[] = '<table>';

      foreach ($contents as $id=>$qty) {

        $sql = 'SELECT * FROM deals WHERE id = '.$id;

        $array = array('id', 'title', 'price', 'qty');

        extract($array);

        echo "$title";

        }

      $output[] = '</table>';

      $output[] = '<p>Grand total: <strong>£'.$total.'</strong></p>';

      $output[] = '<div><button type="submit">Update cart</button></div>';

      $output[] = '</form>';

  } else {

      $output[] = '<p>Your shopping cart is empty.</p>';

  }

  return join('',$output);

}

?>

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.