#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2004
    Location
    Ireland
    Posts
    20
    Rep Power
    0

    Adding and passing qty in cart script


    Hi all
    I followed the cart script from here after googleing and going through all the comments i still can't figure out how to add my own quantity field and have it pass to the cart page, below is the code that i have so far


    Page displaying products
    PHP Code:
    <?php
        
    include("includes/db.php");
        include(
    "includes/functions.php");
        
        if(
    $_REQUEST['command']=='add' && $_REQUEST['productid']>0){
            
    $pid=$_REQUEST['productid'];
            
    addtocart($pid1);
            
    header("location:shoppingcart.php");
            exit();
        }
        
    ?>
    <!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>Products</title>
    <script language="javascript">
        function addtocart(pid, qty){
            document.form1.productid.value=pid;
            document.form1.quantity.value = qty;
            document.form1.command.value='add';
            alert('adding item to list');
            document.form1.submit();
        }
    </script>
    </head>


    <body>
    <form name="form1">
        <input type="hidden" name="productid" />
        <input type="hidden" name="command" />
    </form>
    <div align="center">
        <h1 align="center">Products</h1>
        <table border="0" cellpadding="2px" width="600px">
            <?php
                $result
    =mysql_query("select * from products") or die("select * from products"."<br/><br/>".mysql_error());
                while(
    $row=mysql_fetch_array($result)){
            
    ?>
            <tr>
                <td><img src="<?php echo $row['product_image_big1']?>" /></td>
                <td>       <p><b><?php echo $row['product_name']?></b><br />
                        <?php echo $row['product_description']?><br />
                        Price:<big style="color:green">
                            $<?php echo $row['base_price']?></big><br />
                            Order Quantity: <input name="quantity" type="text" maxlength="4" /><br />
                        
                </p>
                  <p>
      <input type="button" value="Add to Cart" onclick="addtocart(<?php echo $row['product_code']?>, quantity)" />
                  </p>
                </td>
            </tr>
            <tr><td colspan="2"><hr size="1" /></td>
            <?php ?>
        </table>
    </div>
    </body>
    </html>
    functions.php page
    PHP Code:
    <?php
        
    function get_product_name($pid){
            
    $result=mysql_query("select product_name from products where product_code=$pid") or die("select product_name from products where product_code=$pid"."<br/><br/>".mysql_error());
            
    $row=mysql_fetch_array($result);
            return 
    $row['product_name'];
        }
        function 
    get_price($pid){
            
    $result=mysql_query("select base_price from products where product_code=$pid") or die("select product_name from products where product_code=$pid"."<br/><br/>".mysql_error());
            
    $row=mysql_fetch_array($result);
            return 
    $row['base_price'];
        }
        function 
    remove_product($pid){
            
    $pid=intval($pid);
            
    $max=count($_SESSION['cart']);
            for(
    $i=0;$i<$max;$i++){
                if(
    $pid==$_SESSION['cart'][$i]['productid']){
                    unset(
    $_SESSION['cart'][$i]);
                    break;
                }
            }
            
    $_SESSION['cart']=array_values($_SESSION['cart']);
        }
        function 
    get_order_total(){
            
    $max=count($_SESSION['cart']);
            
    $sum=0;
            for(
    $i=0;$i<$max;$i++){
                
    $pid=$_SESSION['cart'][$i]['productid'];
                
    $q=$_SESSION['cart'][$i]['qty'];
                
    $price=get_price($pid);
                
    $sum+=$price*$q;
            }
            return 
    $sum;
        }
        function 
    addtocart($pid,$q){
            if(
    $pid<or $q<1) return;
            
            if(
    is_array($_SESSION['cart'])){
                if(
    product_exists($pid)) return;
                
    $max=count($_SESSION['cart']);
                
    $_SESSION['cart'][$max]['productid']=$pid;
                
    $_SESSION['cart'][$max]['qty']=$q;
            }
            else{
                
    $_SESSION['cart']=array();
                
    $_SESSION['cart'][0]['productid']=$pid;
                
    $_SESSION['cart'][0]['qty']=$q;
            }
        }
        function 
    product_exists($pid){
            
    $pid=intval($pid);
            
    $max=count($_SESSION['cart']);
            
    $flag=0;
            for(
    $i=0;$i<$max;$i++){
                if(
    $pid==$_SESSION['cart'][$i]['productid']){
                    
    $flag=1;
                    break;
                }
            }
            return 
    $flag;
        }

    ?>
    shoppingcart.php page
    PHP Code:
    <?php
        
    include("includes/db.php");
        include(
    "includes/functions.php");
        
        if(
    $_REQUEST['command']=='delete' && $_REQUEST['pid']>0){
            
    remove_product($_REQUEST['pid']);
        }
        else if(
    $_REQUEST['command']=='clear'){
            unset(
    $_SESSION['cart']);
        }
        else if(
    $_REQUEST['command']=='update'){
            
    $max=count($_SESSION['cart']);
            for(
    $i=0;$i<$max;$i++){
                
    $pid=$_SESSION['cart'][$i]['productid'];
                
    $q=intval($_REQUEST['product'.$pid]);
                if(
    $q>&& $q<=999){
                    
    $_SESSION['cart'][$i]['qty']=$q;
                }
                else{
                    
    $msg='Some proudcts not updated!, quantity must be a number between 1 and 999';
                }
            }
        }

    ?>
    <!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>Shopping Cart</title>
    <script language="javascript">
        function del(pid){
            if(confirm('Do you really mean to delete this item')){
                document.form1.pid.value=pid;
                document.form1.command.value='delete';
                document.form1.submit();
            }
        }
        function clear_cart(){
            if(confirm('This will empty your shopping cart, continue?')){
                document.form1.command.value='clear';
                document.form1.submit();
            }
        }
        function update_cart(){
            document.form1.command.value='update';
            document.form1.submit();
        }


    </script>
    </head>

    <body>
    <form name="form1" method="post">
    <input type="hidden" name="pid" />
    <input type="hidden" name="command" />
        <div style="margin:0px auto; width:600px;" >
        <div style="padding-bottom:10px">
            <h1 align="center">Your Shopping Cart</h1>
        <input type="button" value="Continue Shopping" onclick="window.location='products.php'" />
        </div>
            <div style="color:#F00"><?php echo $msg?></div>
            <table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%">
            <?php
                
    if(is_array($_SESSION['cart'])){
                    echo 
    '<tr bgcolor="#FFFFFF" style="font-weight:bold"><td>Serial</td><td>Name</td><td>Price</td><td>Qty</td><td>Amount</td><td>Options</td></tr>';
                    
    $max=count($_SESSION['cart']);
                    for(
    $i=0;$i<$max;$i++){
                        
    $pid=$_SESSION['cart'][$i]['productid'];
                        
    $q=$_SESSION['cart'][$i]['qty'];
                        
    $pname=get_product_name($pid);
                        if(
    $q==0) continue;
                
    ?>
                        <tr bgcolor="#FFFFFF"><td><?php echo $i+1?></td><td><?php echo $pname?></td>
                        <td>$ <?php echo get_price($pid)?></td>
                        <td><input type="text" name="product<?php echo $pid?>" value="<?php echo $q?>" maxlength="3" size="2" /></td>                    
                        <td>$ <?php echo get_price($pid)*$q?></td>
                        <td><a href="javascript:del(<?php echo $pid?>)">Remove</a></td></tr>
                <?php                    
                    
    }
                
    ?>
                    <tr><td><b>Order Total: $<?php echo get_order_total()?></b></td><td colspan="5" align="right"><input type="button" value="Clear Cart" onclick="clear_cart()"><input type="button" value="Update Cart" onclick="update_cart()"><input type="button" value="Place Order" onclick="window.location='billing.php'"></td></tr>
                <?php
                
    }
                else{
                    echo 
    "<tr bgColor='#FFFFFF'><td>There are no items in your shopping cart!</td>";
                }
            
    ?>
            </table>
        </div>
    </form>
    </body>
    </html>
    all help much appreciated.

    thanks
    mskazza
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    Hi,

    the whole form logic is just weird: They write the product code into a JavaScript function call; when you click on the submit button, this code executes, puts the product code into a hidden form field and finally triggers form submission. WTF? No, that's not how you submit a form.

    The quantity stuff you're trying to do there makes even less sense, since the quantity obviously is no predefined, fixed value. It's determined by whatever the user enters into the field -- which is kind of what forms are for.

    This whole thing is a bastardization of basic HTML functionalities. A form already has a submit element, which does exactly that: submit the form. What's the point of re-implementing this with some weird JavaScript code?

    I suggest you throw away this script. It's garbage. Learn HTML. Then learn the PHP basics. And then write your own code. It's really not difficult, it's gonna be much better than this (hopefully), and you'll actually understand what it does. Copying, pasting and modifying usually doesn't get you far, especially when the base code is crap.
    Last edited by Jacques1; June 24th, 2013 at 01:04 PM.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  4. #3
  5. No Profile Picture
    Dazed&Confused
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2002
    Location
    Tempe, AZ
    Posts
    506
    Rep Power
    128
    Dangit. Screwed up my own post and now can't recover what I had. Well, might as well leave what I thought I was putting in a new post...

    Originally Posted by Jacques1
    Jacques1 disagrees: Why on earth do you promote this crappy JavaScript form emulation? I know that you love dissent for
    dissent's sake, but this is just stupid.
    What are you complaining about now? I agreed with you that there was no need for Javascript in this situation.

    Comments on this post

    • Jacques1 disagrees : Why on earth do you promote this crappy JavaScript form emulation? I know that you love dissent for dissent's sake, but this is just stupid.
    Last edited by dmittner; June 25th, 2013 at 03:06 PM.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2004
    Location
    Ireland
    Posts
    20
    Rep Power
    0
    thanks for the replies. i know html, xml, css and basic php but like most beginners have no idea where to start writing a shopping cart from scratch, and when i try to find a tutorial this is the kind of stuff that comes up, non of the tutorials i've come across do what i want them to do and i've no idea where to go from here.

    so maybe instead of just saying that this one is crap you could point me in the right direction and please don't just assume that i don't understand this script, i do. but understanding and trying to modify the script are different. i'm sorry if i seem ungrateful, but i've been trying different carts for couple of months now, even asked a question on here before and all anyone seems to do is tell me that what i have is crap and don't offer any suggestions.

    Please i'm at my wits end, please point me in the right direction if this script is sooo bad.

    sorry and thanks,
    mskazza
  8. #5
  9. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    Not sure why the idea of writing your own shopping cart seems so unthinkable to you.

    Wanna know how I learned HTML, PHP and JavaScript? I wrote code. I had some things I wanted to do, so I learned the basics and then simply started to program. I made a lot of mistakes, I did a lot of trial and error, and the code surely wasn't good. But it worked after a while, I learned from it and got better. Then I started the next project and so on.

    Is this approach really that odd? I don't understand what all those "tutorials" and this copying and pasting are about. Write your own code!

    Of course you should learn from others and see how they do it. We all do that, and it's a great way of improving. But this "I can't do anything without my tutorial" thing just seems stupid to me.

    Anyway, if that's what you're looking for, I can't help you. I don't know any shopping cart tutorials. But what I can help you with is writing your own code. It's not difficult:

    Start with plain HTML. No JavaScript magic, just a simple product list. For every product, add an HTML form with a hidden field for the product ID, a text field for the quantity and a submit button. Again, no JavaScript! Just set the field values with PHP and have the form do its work. That's what it's made for.

    When you're done with that, you're already better than this tutorial will ever be.

    Then go on with the target target page for this form: At first, it's only supposed to take the form input and insert it into the session. Nothing else.

    When you're done with that, extend the target page and have it list the products in the session. Only that, nothing else.

    When that's done as well, all what's left to do is add up the prices at the bottom and add the "remove article" and "change quantity" functionalities. That again will be just a simple HTML form.

    All of these steps are pretty simple, right? Nothing that couldn't be done with basic knowledge. But if you put everything together, you'll actually have a working shopping cart. So why not simply do it? Go through the steps, write your code, and if there's any question, ask it.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2004
    Location
    Ireland
    Posts
    20
    Rep Power
    0
    it doesn't seem so unthinkable, was using tutorials as a guide. however i've started over from scratch. this is what i have so far :

    Products Page

    PHP Code:
    <?php require_once('Connections/adlantic.php'); ?>
    <?php
    if (!function_exists("GetSQLValueString")) {
    function 
    GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
    {
      if (
    PHP_VERSION 6) {
        
    $theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
      }

      
    $theValue function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

      switch (
    $theType) {
        case 
    "text":
          
    $theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
          break;    
        case 
    "long":
        case 
    "int":
          
    $theValue = ($theValue != "") ? intval($theValue) : "NULL";
          break;
        case 
    "double":
          
    $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
          break;
        case 
    "date":
          
    $theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
          break;
        case 
    "defined":
          
    $theValue = ($theValue != "") ? $theDefinedValue $theNotDefinedValue;
          break;
      }
      return 
    $theValue;
    }
    }

    mysql_select_db($database_adlantic$adlantic);
    $query_products "SELECT * FROM products ORDER BY product_name ASC";
    $products mysql_query($query_products$adlantic) or die(mysql_error());
    $row_products mysql_fetch_assoc($products);
    $totalRows_products mysql_num_rows($products);
    ?>
    <!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>Untitled Document</title>
    </head>

    <body> <?php do { ?>
    <form enctype="multipart/form-data" action="cartpagetest.php" method="POST" name="products" title="products">
     
        <table width="200" border="1">
          <tr>
            <td><img src="theme/adlantic/images/products/<?php echo $row_products['product_image_big1']; ?>" width="254" height="274" /></td>
            <td><?php echo $row_products['product_name']; ?></td>
            <td><?php echo $row_products['product_code']; ?></td>
            <td><p>
              <label for="qty"></label>
              Quantity:
              <input type="text" name="quantity" id="qty" />
              </p>
              <p>Colour<br />
                <label for="colour"></label>
                <select name="colour" id="colour">
                  <option value="red">Red</option>
                  <option value="blue">Blue</option>
                  <option value="grn">Green</option>
                </select>
              </p>
              <p>Price<br />
                <label for="price"></label>
                <select name="price" id="price">
                  <option value="1.99">1.99</option>
                  <option value="2.99">2.99</option>
                  <option value="3.99">3.99</option>
                </select>
                <br />
            </p></td>
          </tr>
          <tr>
            <td><?php echo $row_products['product_description']; ?></td>
            <td><?php echo $row_products['min_qty']; ?></td>
            <td><?php echo $row_products['base_price']; ?></td>
            <td><input name="product_code" type="hidden" value="<?php echo $row_products['product_code']; ?>" />
            <input type="submit" name="submit" id="submit" value="Add to Cart!" /></td>
          </tr>
          <tr>
            <td colspan="4"><hr /></td>
          </tr>
        </table>
        
    </form><?php } while ($row_products mysql_fetch_assoc($products)); ?>
    </body>
    </html>
    <?php
    mysql_free_result
    ($products);
    ?>

    cart page

    PHP Code:
    <?php
     
    // Database connect
    $con mysql_connect("localhost","root","helpme");
    if (!
    $con)
      {
      die(
    'Could not connect: ' mysql_error());
      }

    mysql_select_db("adlantic"$con);


    $stamp date("Ymd");
    $ip $_SERVER['REMOTE_ADDR'];
    $orderid "$stamp-$ip";
    $orderid str_replace(".""""$orderid");
    echo(
    $orderid);
    echo 
    "<br>";

    //Parse Values from Form
    $product_code  mysql_real_escape_string(trim($_POST['product_code']));
    echo(
    $product_code);
    echo 
    "<br>";
    $quantity  mysql_real_escape_string(trim($_POST['quantity']));
    echo(
    $quantity);
    echo 
    "<br>";
    $colour  mysql_real_escape_string(trim($_POST['colour']));
    echo(
    $colour);
    echo 
    "<br>";
    $price  mysql_real_escape_string(trim($_POST['price']));
    echo(
    $price);
    echo 
    "<br>";

    $sql="INSERT INTO order_detail (orderid, product_code, quantity, price)
    VALUES
    ('
    $orderid','$_POST[product_code]','$_POST[quantity]','$_POST[price]')";
    if (!
    mysql_query($sql))
      {
      die(
    'Error: ' mysql_error());
      }

    echo 
    "1 record added";

    $query "SELECT * FROM order_detail WHERE orderid = '".$orderid."'";
        
    $result mysql_query($query);



    ?>


    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>adlantic cart page</title>



    </head>

    <body>
    <br /><br />
    Order Id = <?php echo $orderid?>
    <?php
    echo "<table border='1'>
    <tr>
    <th>Product Code</th>
    <th>Quantity</th>
    <th>Price</th>
    </tr>"
    ;

    while(
    $row mysql_fetch_array($result))
      {
      echo 
    "<tr>";
      echo 
    "<td>" $row['product_code'] . "</td>";
      echo 
    "<td>" $row['quantity'] . "</td>";
      echo 
    "<td>" $row['price'] . "</td>";
      echo 
    "</tr>";
      }
    echo 
    "</table>";

    ?>
    <br />

    </body>
    </html>
    now my problem is that everytime someone goes to the cart page it inserts the record again to the database, i'm guessing i should probably put the insert on a different page? or is there a way to put on same page.

    once i get that bit sorted i'll add the remove and add quantity functions (somehow lol)
  12. #7
  13. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    OK, this already looks a lot better than the previous code.

    However, you should definitely update your database code. The old mysql_* functions are obsolete since almost 10 years and will be removed sooner or later. Choose one of the contemporary extensions. I recommend PDO. The new extensions support prepared statements, which are much more secure than manual escaping with mysql_real_escape_string().

    So that would be the next step.

    Regarding the unwanted inserts, you need two things: You have to check if there even was a POST request. Currently, you use the $_POST in any case, even if it's empty. This way you'll end up with an empty row whenever somebody just visits the page.

    Secondly, you should do a redirect after a POST request has been done. This prevents automatic re-submissions when the user reloads the page. See Post/Redirect/Get.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2004
    Location
    Ireland
    Posts
    20
    Rep Power
    0
    First of all thank u very much for your help. This is what i have so far.

    Products page

    PHP Code:
    <?php
    session_start
    ();
    // Database Connection
    $con=mysqli_connect("localhost","root","","adlantic");

    // Check connection
    if (mysqli_connect_errno($con))
      {
      echo 
    "Failed to connect to MySQL: " mysqli_connect_error();
      }


    $result mysqli_query($con,"SELECT * FROM products ORDER BY product_name ASC");

    ?>

    <!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>Untitled Document</title>
    </head>

    <body> <?php do { ?>
    <form enctype="multipart/form-data" action="insertpagetest.php" method="POST" name="products" title="products">
     
        <table width="200" border="1">
          <tr>
            <td><img src="theme/adlantic/images/products/<?php echo $row['product_image_big1']; ?>" width="254" height="274" /></td>
            <td><?php echo $row['product_name']; ?></td>
            <td><?php echo $row['product_code']; ?></td>
            <td><p>
              <label for="qty"></label>
              Quantity:
              <input type="text" name="quantity" id="qty" />
              </p>
              <p>Colour<br />
                <label for="colour"></label>
                <select name="colour" id="colour">
                  <option value="red">Red</option>
                  <option value="blue">Blue</option>
                  <option value="grn">Green</option>
                </select>
              </p>
              <p>Price<br />
                <label for="price"></label>
                <select name="price" id="price">
                  <option value="1.99">1.99</option>
                  <option value="2.99">2.99</option>
                  <option value="3.99">3.99</option>
                </select>
                <br />
            </p></td>
          </tr>
          <tr>
            <td><?php echo $row['product_description']; ?></td>
            <td><?php echo $row['min_qty']; ?></td>
            <td><?php echo $row['base_price']; ?></td>
            <td><input name="product_code" type="hidden" value="<?php echo $row['product_code']; ?>" />
            <input type="submit" name="submit" id="submit" value="Add to Cart!" /></td>
          </tr>
          <tr>
            <td colspan="4"><hr /></td>
          </tr>
        </table>
        
    </form><?php } while ($row mysqli_fetch_assoc($result)); ?>
    </body>
    </html>
    insert record page
    PHP Code:
    <?php
    session_start
    ();
    // Database Connection
    $con=mysqli_connect("localhost","root","","adlantic");

    // Check connection
    if (mysqli_connect_errno($con))
      {
      echo 
    "Failed to connect to MySQL: " mysqli_connect_error();
      }

    $stamp date("Ymd");
    $ip $_SERVER['REMOTE_ADDR'];
    $orderid "$stamp-$ip";
    $orderid str_replace(".""""$orderid");

    $_SESSION['orderid'] = $orderid;

    //Parse Values from Form
    $product_code  mysql_real_escape_string(trim($_POST['product_code']));
    $quantity  mysql_real_escape_string(trim($_POST['quantity']));
    $colour  mysql_real_escape_string(trim($_POST['colour']));
    $price  mysql_real_escape_string(trim($_POST['price']));


    mysqli_query($con,"INSERT INTO order_detail (orderid, product_code, quantity, price)
    VALUES
    ('
    $orderid','$_POST[product_code]','$_POST[quantity]','$_POST[price]')");
       


    header('Location: cartpagetest.php');
        
    ?>
    cart page
    PHP Code:
    <?php
    session_start
    ();
    // Database Connection
    $con=mysqli_connect("localhost","root","","adlantic");

    // Check connection
    if (mysqli_connect_errno($con))
      {
      echo 
    "Failed to connect to MySQL: " mysqli_connect_error();
      }


    $orderid $_SESSION['orderid'];


    $result mysqli_query($con,"SELECT * FROM order_detail, products WHERE order_detail.product_code = products.product_code AND orderid = '".$orderid."'");
        


    ?>


    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>adlantic cart page</title>



    </head>

    <body>
    <br /><br />
    Order Id = <?php echo $orderid?>
    <?php
    echo "<table border='1'>
    <tr>
    <th>Product Code</th>
    <th>Product Name</th>
    <th>Quantity</th>
    <th>Unit Price</th>
    <th>Total Product Price</th>
    <th>Remove</th>
    </tr>"
    ;

    while(
    $row mysqli_fetch_array($result))
      {
      echo 
    "<tr>";
      echo 
    "<td>" $row['product_code'] . "</td>";
      echo 
    "<td>" $row['product_name'] . "</td>";
      echo 
    "<td>" $row['quantity'] . "</td>";
      echo 
    "<td>" $row['price'] . "</td>";
      
    $linetotal $row['quantity'] * $row['price'];
      echo 
    "<td>" $linetotal ."</td>";
      echo 
    "<td>remove link here </td>";
      echo 
    "</tr>";
      }
    echo 
    "</table>";

    $grand_total 0;
    while(
    $row mysqli_fetch_array$result )) {
           
           
    $sub_total $row['quantity'] * $row['price'];
           
    $grand_total += $subtotal;
           echo 
    $sub_total ;

           
    }
    echo 
    $grand_total;
    ?>
    <br />

    </body>
    </html>

    Its actually starting to look like a cart
    I decided to split the script and put in a seperate insert page using sessions to pass the orderid to the cart.
    As you can see on the cart page i've been trying to add up the line totals, but I can't quite figure out how to do it, I managed to get the line totals but now can't add those up to a subtotal.

    Your thought on what I have so far would (are) much appreciated.

    MsKazza
  16. #9
  17. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    Switching to MySQLi was a good decision. However, you've not really completed that transition. When you continue to use unsafe practices (inserting user-defined variables into query strings) and merely add an "i" after every mysql_* function, that doesn't really get you anywhere. Your code is still wide open to SQL injections. "Funny" thing is: You do actually escape the user input, but then you discard everything and instead insert the raw POST values, allowing anybody to manipulate your queries and do pretty much anything with your database.

    You need to actually use the security features offered by MySQLi. Most importantly, you need to replace your unsafe dynamic queries with dynamic queries (see the examples on the page).

    Your code is also vulnerable to cross-site scripting, which means people can inject HTML or JavaScript on your page in order to manipulate it or steal passwords or session cookies.

    Check The 6 worst sins of security.

    I don't know if this is just a fun project or an actual online shop. But if you plan to put this code online some day, it must be secure. Having your server "hacked" and your user data stolen can get you into a lot of trouble.

    As to the code itself:

    I'm not really sure why you've set up a new page. First of all, it doesn't solve the problem: You still insert an empty row whenever somebody visits the page (or reloads it). Secondly, it doesn't really make sense from an "architectural" point of view. If you wanna insert an article to the shopping cart, it's only natural to do that with a POST request to the shopping cart page. That's pretty much exactly the purpose of the POST method. Setting up a separate page to insert the article and then redirect to the shopping cart is rather odd.

    So put the insertion logic back into the shopping cart page. And then add a check for empty($_POST) and a redirect to the page itself as suggested above.

    If you're worried that the shopping cart script may get too complicated, use functions to structure your code.

    In your subtotal code, there's a typo: $subtotal is not the same as $sub_total. You should think about using an IDE (integrated development environment) instead of a simple editor. It will point out typical errors like this right when you make them.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".

IMN logo majestic logo threadwatch logo seochat tools logo