PHP Passing Value on Cart

2019-06-10 23:20发布

问题:

I have created a shopping cart page using PHP. Now the problem I encountered was that, when I add a product to the cart from the product list, what happens is that only the 1st product on the list is added.

When I add another product (since every product on the list has it's own Add to Cart button), the 1st product is added again. Doesn't matter what item I choose, it still end up with the 1st product being added.

Am I missing something?

Here's my code:

Product List:

    <?php do { ?>
         <tr>
          <td colspan="2"><font face="times new roman" size="3"><center><?php echo $prorow['pname']; ?></td>
          <td colspan="1"><font face="times new roman" size="3"><center><?php echo $prorow['pdesc']; ?></td>
          <td colspan="1"><font face="times new roman" size="3"><center><?php echo $prorow['price']; ?></td>
          <td colspan="1"><center><img src="admin/<?php echo $prorow['image']; ?>" width="80" height="80" />
          <td colspan="1">
              <input type="submit" name="addtocart" value="Add to Cart">
          </td>
        </tr>
    <?php } while ($prorow = mysqli_fetch_assoc($result)); ?>

I am passing values using hidden input types.

Add to Cart:

<?php
ob_start();
$con = mysqli_connect('localhost', 'abra', 'abra','abra') or die("Could not connect database");

    $cname = mysql_escape_string($_POST['user']);
    $pid=mysql_escape_string($_POST['proID']);
    $pname=mysql_escape_string($_POST['proName']);
    $price=mysql_escape_string($_POST['proPRICE']);
    $qty=mysql_escape_string($_POST['qty']);


$addtocart = "INSERT INTO cart_track (bid, cName, pname, price, qty) VALUES ('$pid', '$cname', '$pname', '$price', '$qty')";

mysqli_query($con,$addtocart);
header("location:showcart.php");
exit;

ob_end_flush()
 ?>

Show Cart:

<?php
$con = mysqli_connect('localhost', 'abra', 'abra','abra') or die("Could not connect database");

 //Check if user wants to checkout or shop:
if(isset($_POST['checkout']))
{

    header("location:orders.php");
}
if(isset($_POST['shop']))
{
    header("location:prodtable.php");
}
//retrieve items . use session_id and/or datetime
//$PHPSESSID=session_id();
$showcart = "SELECT * from cart_track INNER JOIN products ON bid=pId WHERE bid=pId";
$result=mysqli_query($con, $showcart);


if(!$result)
{
$err=true;
//i recommend writing this error to a log or some text file, for security reasons.
$errmsg=mysql_error();
}
else
{
$err=false;
$num=mysqli_num_rows($result);
}
?>

I suspect that the mistake is on the Product List code, but I have the AddtoCart file checked also.

回答1:

This isn't an answer to fix OPs question, but a section to fix some of OPs "mistakes"

header()

When you're sending a header, make sure you exit; or die; straight after, as you want the code to stop and not process anymore.

header("location:prodtable.php");
die;

mysql and mysqli

Choose one or the other. Preferably mysqli as mysql is deprecated.

This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used

Indentation

You have a mixture of indentation "techniques" and code design. Stick to one.

  • Sometimes you have { on the same line as the condition, sometimes you have it on the new line.
  • Sometimes you have indentation, sometimes you don't.

Validate and sanitize input

You're relying too heavily on mysql_real_escape_string() which;

  • Is part of a deprecated library
  • Doesn't validate the input

Please validate the input before trying to insert it into the database. This will save a headache later should you expect something to be in the database and because of no data validation earlier, a particular system may fall over (and have a knock on effect).

  Is foo an int -------------- Kill process, tell user.
       |             (NO)
       | (YES)
       |
       |
   Ok. Do further checks

Comments

Please use more of these, for your own sake.

Yes, I know this isn't codereview.se, but they needed to be addressed. I've seen so many question that this post should apply to.



回答2:

Ok, here's the Product List.

    <!----- PHP CODES HERE ---------->
    <?PHP
    $con = mysqli_connect('localhost', 'abra', 'abra','abra') or die("Could not connect database");

$result=mysqli_query($con, "SELECT * FROM products");
$prorow = mysqli_fetch_assoc($result);

   ?>

<!-- TOP BAR -->
<div id="top-bar">

    <div class="page-full-width cf">

        <ul id="nav" class="fl">

        <?php   
            session_start();
            if(isset($_SESSION['SES_UNAME']))
                {
                    echo "<li class='v-sep'><a href='profile.php' class='round button dark menu-user image-left'>Logged in as <strong>".$_SESSION['SES_UNAME']."</strong></a></li>";
                }
            else
                {
                    header('location:   /loraine_mod/index.php');
                    exit();
                }
        ?>  


            <li class="v-sep"><a class="round button dark" href="index.php">Home</a></li>
            <li class="v-sep"><a class="round button dark" href="prodtable.php">Product List</a></li>
            <li class="v-sep"><a class="round button dark" href="cart.php">My Cart</a></li>
            <li class="v-sep"><a href="logout.php" class="round button dark menu-logoff image-left">Log out</a></li>

        </ul> <!-- end nav -->

    </div> <!-- end full-width -->  

</div> <!-- end top-bar -->


<!-- MAIN CONTENT -->
<div id="content">

            <div class="content-module">

                <div class="content-module-main" align='center'>
                <form method="POST" action="addtocart.php">
                    <table cols='5'>
                        <font face='algerian'>
                        <thead>

                            <tr>
                                <th colspan="2"><font face='times new roman' size='3'><center>Name</th>
                                <th colspan="1"><font face='times new roman' size='3'><center>Description</th>
                                <th colspan="1"><font face='times new roman' size='3'><center>Price</th>
                                <th colspan="1"><font face='times new roman' size='3'><center>Image</th>
                                <th colspan="1"><font face='times new roman' size='3'><center>Actions</th>
                            </tr>

                        </thead>

                                        <input name="proID" type="hidden" value="<?php echo $prorow['pId']?>">
                                        <input name="proName" type="hidden" value="<?php echo $prorow['pname']?>">
                                        <input name="proPRICE" type="hidden" value="<?php echo $prorow['price']?>">
                                        <input name="user" type="hidden" value="<?php echo $_SESSION['SES_UNAME'] ?>">                      

                        <?php do { ?>
                                    <tr>
                                        <td colspan="2"><font face="times new roman" size="3"><center><?php echo $prorow['pname']; ?></td>
                                        <td colspan="1"><font face="times new roman" size="3"><center><?php echo $prorow['pdesc']; ?></td>
                                        <td colspan="1"><font face="times new roman" size="3"><center><?php echo $prorow['price']; ?></td>
                                        <td colspan="1"><center><img src="admin/<?php echo $prorow['image']; ?>" width="80" height="80" />

                                        <td colspan="1">
                                            <input type="submit" name="addtocart" value="Add to Cart">
                                        </td>

                                    </tr>

                                 <?php } while ($prorow = mysqli_fetch_assoc($result)); ?>

                    </table>
                </form>
                </div> <!-- end content-module-main -->         
    </div> <!-- end content-module -->

Thanks for the suggestions, I'll take those.



回答3:

Your input fields are outside your do loop, so the value will always stay the same - ie: will always be the first product.

<?php do { ?>
    <tr>
        <td colspan="2"><font face="times new roman" size="3"><center><?php echo $prorow['pname']; ?></td>
    <td colspan="1"><font face="times new roman" size="3"><center><?php echo $prorow['pdesc']; ?></td>
        <td colspan="1"><font face="times new roman" size="3"><center><?php echo $prorow['price']; ?></td>
            <td colspan="1"><center><img src="admin/<?php echo $prorow['image']; ?>" width="80" height="80" />

                <td colspan="1">
                    <input name="proID" type="hidden" value="<?php echo $prorow['pId'] ?>">
                    <input name="proName" type="hidden" value="<?php echo $prorow['pname'] ?>">
                    <input name="proPRICE" type="hidden" value="<?php echo $prorow['price'] ?>">
                    <input name="user" type="hidden" value="<?php echo $_SESSION['SES_UNAME'] ?>">  
                    <input type="submit" name="addtocart" value="Add to Cart">
                </td>

                </tr>

            <?php } while ($prorow = mysqli_fetch_assoc($result)); ?>

            </table>


回答4:

Already fixed. The error (logical) was coming from a javascript used to update the shoppingcart page.

<script language="javascript">
function addtocart(pid){
    document.form1.productid.value=pid;
    document.form1.command.value='add';
    document.form1.submit();
}
</script>

Anyway. Thanks for your your answer guys. Will be posting a question in regards to this.