Jump to content

Items wont show in shopping cart


hass1980

Recommended Posts

Hi,

 

I cant get any products to be displayed in the shopping cart as I keep getting ht e following errors.

 

Notice: Query failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',,,,)' at line 1 SQL: SELECT * FROM product WHERE productid IN (1,,,,,,) in C:\wamp\www\myproject\inc\mysql.class.php on line 114

 

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\wamp\www\myproject\inc\mysql.class.php on line 156

 

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\wamp\www\myproject\inc\mysql.class.php on line 172

 

Code for the mysql.class.php

 


<?php
ob_start();
/**
* Hide Notice errors. Mostly returned when it finds an undeclared variable.
*/
error_reporting(E_ALL & ~E_NOTICE);
/**
* 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 $dbUser;

    /**
    * MySQL user's password
    * @access private
    * @var string
    */
    var $dbPass;

    /**
    * Name of database to use
    * @access private
    * @var string
    */
    var $dbName;

    /**
    * 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,$dbUser,$dbPass,$dbName) {
        $this->host=$host;
        $this->dbUser=$dbUser;
        $this->dbPass=$dbPass;
        $this->dbName=$dbName;
        $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->dbUser,
                                      $this->dbPass)) {
            trigger_error('Could not connect to server');
            $this->connectError=true;
        // Select database
        } else if ( !@mysql_select_db($this->dbName,$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
    */
    function query($sql) {
        if (!$queryResource=mysql_query($sql,$this->dbConn))
            trigger_error ('Query failed: '.mysql_error($this->dbConn).
                           ' SQL: '.$sql);
        return new MySQLResult($this,$queryResource);
    }
}

/**
* 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();
    }
}
?>

 

Code for the functions.inc.php

 


<?php	
/**
* To Display the user shopping cart
* @return string
*/	
function showCart()
{
    global $db;
    /**
     * Varibale declaration.
*/
    $price	=	'';
    $qty	='';
    $cart   = $_SESSION['cart'];
    $total  = 0;
    $output = '';
    
    $output  = '<form action="cart.php?action=update" method="post" id="contents">';
    $output .= '<h4>Shopping Cart</h4><br>';
    $output .= "<table cellpadding='0' cellspacing='0' width='98%' border='0' align='center' class='tableborder2'>
                <tr valign='middle' height='30'>
                    <td align='left' class='listbg'> </td>
                    <td align='left' class='listbg'>Product</td>
                    <td align='left' class='listbg'>Product Price</td>
                    <td align='left' class='listbg'>Quantity</td>
                    <td align='left' class='listbg'>Total</td>
                </tr>";
    if ($cart)
    {
        $items    = explode(',',$cart);
        $contents = array();
        foreach ($items as $item)
        {
            $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
        }
        
        $sql    = "SELECT * FROM product WHERE productid IN ($cart)";
        $result = $db->query($sql);
        while ($row = $result->fetch())
        {
            extract($row);
            $qty = $contents[$id];
            $output .= "<tr valign='middle' height='30' class='list1bg' onmouseover='this.className=\"list2bg\"' onmouseout='this.className=\"list1bg\"'>
                        <td align='left' class='normaltext'><a href='cart.php?action=delete&id=$id' class='r'>Remove</a></td>
                        <td align='left' class='normaltext'>$name by $description</td>
                        <td align='left' class='normaltext'>£ $price</td>
                        <td align='left' class='normaltext'><input type='text' name='qty$id' value='$qty' size='3' maxlength='3' /></td>
                        <td align='left' class='normaltext'>£".($price * $qty)."</td>
                    </tr>";
            $total += $price * $qty;
        }
    }
    else
        $output .= "<tr valign='middle' height='30'>
                        <td colspan='10 class='message'> No Products In Shopping Cart</td>
                    </tr>";
     $output .= "<tr valign='middle' height='30' class='list1bg' onmouseover='this.className=\"list2bg\"' onmouseout='this.className=\"list1bg\"'>
                 <td colspan='4' class='normalbold' align='right'>Grand Total : </td>
                 <td align='left' class='normaltext'>£".($price * $qty)."</td>
             </tr>";
     $button = '';
     if ($cart)
        $button = '<button type="submit">Update cart</button>';
     $output .= "<tr valign='middle' height='30' class='list1bg' onmouseover='this.className=\"list2bg\"' onmouseout='this.className=\"list1bg\"'>
                 <td colspan='2' class='normalbold' align='right'>$button</td>
                 <td colspan='2' class='normalbold' align='right'>Grand Total : </td>
                 <td align='left' class='normaltext'>£".($price * $qty)."</td>
             </tr>";
        
    $output .= '</table>';
    $output .= '</form>';
    
    return $output;
}

/**
* To reformat the string to input to the database
* @return string
*/	
function GetSQLValueString($theValue, $theType='', $theDefinedValue = "", $theNotDefinedValue = "") 
{
    $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;	
    switch ($theType) 
    {
        case "text":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "''";
            break;    
        case "long":
        case "int":
            $theValue = ($theValue != "") ? intval($theValue) : 0;
            break;
        case "double":
            $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "''";
            break;
        case "date":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "''";
            break;
        case "defined":
            $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
            break;
    }
    
    return $theValue;
}

/**
* User login methods
*/	
function loginUser()
{
    global  $db;
    
    $username = GetSQLValueString($_POST['username'],'text');
    $password = GetSQLValueString($_POST['password'],'text');
    
    $customers_sql = "SELECT * FROM ".CUSTOMER_TABLE." AS CU,".LOGIN_TABLE." AS LO WHERE CU.CustomerID=LO.CustomerID AND LO.Username=$username AND LO.Password=$password";
    $customers_result = $db->query($customers_sql);
    if($customers_result->size()>0)
    {
        $customers_row = $customers_result->fetch();
        $_SESSION['CustomerID'] = $customers_row['CustomerID'];
    }
}

/**
* User registration methods
*/	
function registerUser()
{
    global  $db;
    
    $forename = GetSQLValueString($_POST['forename'],'text');
    $surname  = GetSQLValueString($_POST['surname'],'text');
    $add1     = GetSQLValueString($_POST['add1'],'text');
    $add2     = GetSQLValueString($_POST['add2'],'text');
    $add3     = GetSQLValueString($_POST['add3'],'text');
    $postcode = GetSQLValueString($_POST['postcode'],'text');
    $phone    = GetSQLValueString($_POST['phone'],'text');
    $email    = GetSQLValueString($_POST['email'],'text');
    $username = GetSQLValueString($_POST['username'],'text');
    $password = GetSQLValueString($_POST['password'],'text');
    
    $customer_sql    = "INSERT INTO ".CUSTOMER_TABLE."(Forename,Surname,Add1,Add2,Add3,Postcode,Phone,Email) VALUES ($forename,$surname,$add1,$add2,$add3,$postcode,$phone,$email)";
    echo $customer_sql; exit;
    $customer_result = $db->query($customer_sql);
    $customer_id = $customer_result->insertID();
    
    $customer_sql = "INSERT INTO ".LOGIN_TABLE."(CustomerID,Username,Password) VALUES ($customer_id,$username,$password)";
    $db->query($customer_sql);
    
    $_SESSION['CustomerID'] = $customer_id;
    
    return header("Location: index.php");
    exit;
}

/**
* Update user methods
*/	
function updateUser()
{
    global  $db;
    
    $customer_id = $_SESSION['CustomerID'];
    
    $forename = GetSQLValueString($_POST['forename'],'text');
    $surname  = GetSQLValueString($_POST['surname'],'text');
    $add1     = GetSQLValueString($_POST['add1'],'text');
    $add2     = GetSQLValueString($_POST['add2'],'text');
    $add3     = GetSQLValueString($_POST['add3'],'text');
    $postcode = GetSQLValueString($_POST['postcode'],'text');
    $phone    = GetSQLValueString($_POST['phone'],'text');
    $email    = GetSQLValueString($_POST['email'],'text');
    $username = GetSQLValueString($_POST['username'],'text');
    $password = GetSQLValueString($_POST['password'],'text');
    
    $customer_sql = "UPDATE ".CUSTOMER_TABLE." SET forename=$forename,surname=$surname,Add1=$add1,Add2=$add2,Add3=$add3,Postcode=$postcode,Phone=$phone,Email=$email WHERE CustomerID='$customer_id'";
    $db->query($customer_sql);
    
    $customer_sql = "UPDATE ".LOGIN_TABLE." SET Username=$username,Password=$password WHERE CustomerID='$customer_id'";
    $db->query($customer_sql);
    
    return header("Location: myaccount.php?action=myaccount");
    exit;
}

/**
* To display the user login, registration and myaccount page
* @return string
*/	
function myAccount()
{
    global $db;
    $content = '';
    
    switch ($_POST['action'])
    {
       	case 'login':
       	        loginUser();
       		       break;
       		       
       	case 'register':
       	        registerUser();
       		       break;
       		       
       	case 'myaccount':  
       	        updateUser();     	 
       		       break;
    }
    
    switch ($_GET['action'])
    {
       	case 'login':
       	        $content = "
<form method='POST' onsubmit='return loginCheck()' id='tableclass'>
<input type='hidden' name='action' value='login'>
<h4>Login</h4>
<table cellpadding='0' cellspacing='0' width='100%' border='0' align='center'>
    <tr valign='middle' height='30'>
        <td align='right' width='50%'>Username : </td>
        <td align='left' width='50%'><input type='text' name='username' id='username' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Password : </td>
        <td align='left'><input type='password' name='password' id='password' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td colspan='2' align='center'>
            <input type='submit' value='     Login     ' name='btn_lgn'>
            <input type='reset' value='     Cancel     ' name='btn_cel'>
        </td>
    </tr>
</table>
<br>
</form>";       	 
       		       break;
       		       
       	case 'register':
       	        $content = "
<form method='POST' id='tableclass' name='registerform'>
<input type='hidden' name='action' value='register'>
<h4>Create an account</h4>
<table cellpadding='0' cellspacing='0' width='100%' border='0' align='center'>
    <tr valign='middle' height='30'>
        <td align='right' width='50%'>First Name : </td>
        <td align='left' width='50%'><input type='text' name='forename' id='forename' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Last Name : </td>
        <td align='left'><input type='text' name='surname' id='surname' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Address 1 : </td>
        <td align='left'><input type='text' name='add1' id='add1' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Address 2 : </td>
        <td align='left'><input type='text' name='add2' id='add2' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Address 3 : </td>
        <td align='left'><input type='text' name='add3' id='add3' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Postcode : </td>
        <td align='left'><input type='text' name='postcode' id='postcode' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Phone Number : </td>
        <td align='left'><input type='text' name='phone' id='phone' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Email Address : </td>
        <td align='left'><input type='text' name='email' id='email' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Username : </td>
        <td align='left'><input type='text' name='username' id='username' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Password : </td>
        <td align='left'><input type='password' name='password' id='password' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Re-enterPassword : </td>
        <td align='left'><input type='password' name='password1' id='password1' value=''></td>
    </tr>
    <tr valign='middle' height='30'>
        <td colspan='2' align='center'>
            <input type='button' value='     Register     ' name='btn_reg' onclick='registerCheck()'>
            <input type='reset' value='     Cancel     ' name='btn_cel'>
        </td>
    </tr>
</table>
<br>
</form>";       	 
       		       break;
       		       
       	case 'myaccount':
       	        $customers_sql    = "SELECT * FROM customers AS CU,logins AS LO WHERE CU.id=LO.customer_id AND LO.customer_id=".$_SESSION['CustomerID'];
                $customers_result = $db->query($customers_sql);
                $customers_row    = $customers_result->fetch();
       	        $content = "
<form method='POST' id='tableclass' name='registerform'>
<input type='hidden' name='action' value='myaccount'>
<h4>Myaccount</h4>
<table cellpadding='0' cellspacing='0' width='100%' border='0' align='center'>
    <tr valign='middle' height='30'>
        <td align='right' width='50%'>First Name : </td>
        <td align='left' width='50%'><input type='text' name='forename' id='forename' value='".$customers_row['forename']."'></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Last Name : </td>
        <td align='left'><input type='text' name='surname' id='surname' value='".$customers_row['surname']."'></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Address 1 : </td>
        <td align='left'><input type='text' name='add1' id='add1' value='".$customers_row['add1']."'></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Address 2 : </td>
        <td align='left'><input type='text' name='add2' id='add2' value='".$customers_row['add2']."'></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Address 3 : </td>
        <td align='left'><input type='text' name='add3' id='add3' value='".$customers_row['add3']."'></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Postcode : </td>
        <td align='left'><input type='text' name='postcode' id='postcode' value='".$customers_row['postcode']."'></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Phone Number : </td>
        <td align='left'><input type='text' name='phone' id='phone' value='".$customers_row['phone']."'></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Email Address : </td>
        <td align='left'><input type='text' name='email' id='email' value='".$customers_row['email']."'></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Username : </td>
        <td align='left'><input type='text' name='username' id='username' value='".$customers_row['username']."'></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Password : </td>
        <td align='left'><input type='password' name='password' id='password' value='".$customers_row['password']."'></td>
    </tr>
    <tr valign='middle' height='30'>
        <td align='right'>Re-enterPassword : </td>
        <td align='left'><input type='password' name='password1' id='password1' value='".$customers_row['password']."'></td>
    </tr>
    <tr valign='middle' height='30'>
        <td colspan='2' align='center'>
            <input type='button' value='     Update Details     ' name='btn_reg' onclick='myaccountCheck()'>
        </td>
    </tr>
</table>
<br>
</form>";       	 
       		       break;
       		       
       	case 'logout':
       	        session_unregister('customer_id');       	        
       		       break;
       		       
       	default:
       	        return header("Location: index.php");
       		       break;
    }
    if((isset($_SESSION['CustomerID']) && $_SESSION['CustomerID']>0 && ($_REQUEST['action']=='login' || $_REQUEST['action']=='register')) || (!isset($_SESSION['CustomerID']) && ($_REQUEST['action']=='myaccount' || $_REQUEST['action']=='logout')))
    {
        return header("Location: index.php");
        exit;
    }
    
    return $content;
}

/**
* To display user side header
* @return string
*/	
function siteHeader()
{
    echo '
    <!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">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>PHP Shopping Cart Demo &#0183; Bookshop</title>
        <LINK REL=StyleSheet HREF="css/style.css" TYPE="text/css"  />
        <script src="js/ajax.js"></script>
        <script src="js/common.js"></script>
    </head>
    <body>
    
    <div id="wrapper">
       
    <div id="header"></div>
    <div id="navigation">'.writeShoppingCart().'</div>
    
    <div id="leftcolumn">
        <p align="left"> </p>
        <h4> </h4>
        <h4>Browse by Category</h4>
        <ul id="nav">
            <p> </p>
            <a href="index.php">Home</a>
            '.categoryListing().'
            <a href="">Contact Us</a>
        </ul>
    </div>
    <div id="rightcolumn">';
}


/**
* To display user side footer
* @return string
*/	
function siteFooter()
{
    echo '
    </div>
    <div id="footer"><p> </p><p> </p>
    </div>
    
    </body>
    </html>';
}


/**
* To display user top links
* @return string
*/	
function writeShoppingCart()
{
//    $cart = $_SESSION['cart'];
//    if (!$cart)
//    {
//        $head = '<p>You have no items in your shopping cart</p>';
//    }
//    else
//    {
//        // Parse the cart session variable
//        $items = explode(',',$cart);
//        $s = (count($items) > 1) ? 's':'';
//        $head = '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';


//    }
   $head	=	'';
    $head .= '<a href="index.php">Home</a> | <a href="cart.php">Shopping Cart</a> | ';
    if(isset($_SESSION['CustomerID']) && $_SESSION['CustomerID']>0)
        $head .= '<a href="myaccount.php?action=myaccount">My account</a> | <a href="myaccount.php?action=logout">Logout</a></p>';
    else 
        $head .= '<a href="myaccount.php?action=login">Login</a> | <a href="myaccount.php?action=register">Create an account</a></p>';
        
    return $head;
}

/**
* To display the leftside/center categories
* @return string
*/	
function categoryListing($flag=0)
{ 
    global $db;
    
    $categories_sql    = "SELECT * FROM ".CATEGORY_TABLE." WHERE 1 ORDER BY CatName ASC";
    $categories_result = $db->query($categories_sql);
    $categories        = '';
    if($flag==1)
        $categories = '<h4>Browse by Category</h4><p> </p><p> </p>';
    if($categories_result->size()>0)
    {
        $i   = 0;
        $row = 5;
        while ($categories_row = $categories_result->fetch())
        {
            $CatID    = $categories_row['CatID'];
            $CatName  = $categories_row['CatName'];
            $CatImage = $categories_row['CatImage'];
            
            (isset($_GET['cat_id']) && $_GET['cat_id']==$CatID) ? $class='selected' : $class='';
            
            if($flag==0)
                $categories .= "<a href='index.php?cat_id=$CatID' class='$class'>$CatName</a>";
            else 
            {
                $categories .= "
                    <div class='img'>
                        <a href='index.php?cat_id=$CatID'><img src='images/category/$CatID.$CatImage' alt='storage' width='110' height='90' /></a>
                        <div class='desc'>$CatName</div>
                    </div>";
            }
        }
    }
    
    return $categories;
}

/**
* To display products in the specified category
* @return string
*/	
function productListing()
{ 
    global $db;
    
    $cat_id   = $_GET['cat_id'];
    
    $categories_sql    = "SELECT * FROM ".CATEGORY_TABLE." WHERE CatID='$cat_id'";
    $categories_result = $db->query($categories_sql);
    if($categories_result->size()==0)
    {
        return header("Location: index.php");;
        exit;
    }
    $categories_row    = $categories_result->fetch();
    $caregory_name     = $categories_row['CatName'];
    
    $products_sql = "SELECT * FROM ".PRODUCT_TABLE." WHERE CatID='$cat_id' ORDER BY ProductName ASC";
    $products_result = $db->query($products_sql);
    $products = "<h4>Products in \"$caregory_name\"</h4><br>";
    if($products_result->size()>0)
    {
        while ($products_row = $products_result->fetch())
        {
            $product_id    = $products_row['ProductID'];
            $product_name  = $products_row['ProductName'];
            $product_desc  = $products_row['ProductDesc'];
            $product_price = $products_row['ProductPrice'];
            $product_image = $products_row['ProductImage'];
            
            $products .= "
            <div class='img'>
                <a href=''><img src='images/product/$product_id.$product_image' alt='storage' width='110' height='90' /></a>
                <div class='desc'>\"$product_name\" by $product_desc</div>
                <div class='desc'>£ $product_price</div>
                <div class='desc'><a href='cart.php?action=add&id=$product_id'>Add to cart</a></div>
            </div>";
        }
    }
    else 
    {
        $products .= "<div class='message'><br><br>No Products Found</div>";
    }
//    $products .= "<div style='clear:both'></div>";
//    $products .= categoryListing(2);
    
    return $products;
}
?>



Link to comment
https://forums.phpfreaks.com/topic/156547-items-wont-show-in-shopping-cart/
Share on other sites

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.