0

i am trying to delete one row from a table based on the selection of the user:

<form method="post" action="updatecart.php"> 
<td> <button class="btn" type="submit" name="update" >Update</button></td>
<td> <button class="btn" type="submit" name="remove" >Remove</button></td>
<input type="hidden" name="itemid[]" value=<?php echo"$row[3]"?>>
<input type="hidden" name="cartid[]" value=<?php echo"$row[6]"?>>
<td><a href="product_detail.html"><img alt="" src="/photos/<?php echo"$row[4]"?> " width= 100 height=100></a></td>
<td><?php echo"$row[0]"?></td>
<td><input type="number" id="quantity" name="quantity[]" min=1 max=<?php echo"$row[5]"?> value=<?php 
echo"$row[1]"?>></td>
<td><?php echo"$row[2]"?></td>
<?php $total = $total * $row[1]?>
<td><?php echo"$total"?></td>
</tr>
<?php $totaloftotal+=$total; ?>

whenever the use presses the remove button only the selected item, but what happens is everything gets deleted.

this is the

    elseif(isset($remove)){
        for($z= 0; $z <count($itemid); $z++ ){
    try{
        require('connection.php');
        $cartid= $_POST["cartid"];
        $itemid= $_POST["itemid"];  
        $qty= $_POST["quantity"];
        $sql2= "delete from cart where qty=$qty[$z] and iid=$itemid[$z] and cart_id=$cartid[$z] and uid=$uid";
        $x = $db->exec($sql2);

the update works just fine, i only have a problem with the delete.. help.

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
nan
  • 1
  • 1
  • 1
    (Possible) side note: Do not use string interpolation or concatenation to get values into SQL queries. That's error prone and might make your program vulnerable to SQL injection attacks. Use parameterized queries. See ["How to include a PHP variable inside a MySQL statement"](https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement) and ["How can I prevent SQL injection in PHP?"](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – sticky bit Dec 30 '20 at 11:31
  • 1
    Your HTML is invalid. You cannot nest table elements within a form as you are doing here - the form must either contain the entire table or the form must be wholly contained within a single table cell – Professor Abronsius Dec 30 '20 at 11:38
  • Is the snippet of HTML that you have shown generated in a loop based upon a recordset? – Professor Abronsius Dec 30 '20 at 11:41
  • 1
    I'm assuming that this `require('connection.php')` is where you define `$db`? Don't include it on _every iteration_ since that will create a new connection to the database for every item in the array. That's not a good thing. Just include it once before the loop an reuse the same connection. – M. Eriksson Dec 30 '20 at 12:04
  • yes it is where i defined the $db, but is it what causes the problen? @MagnusEriksson – nan Dec 30 '20 at 12:13
  • @ProfessorAbronsius yes it is generated using: while($row = $rs->fetch()), in order to fetch multiple rows from the database. – nan Dec 30 '20 at 12:15
  • Your loop iterates through from 0 to count(items) and deletes each one is why they all get deleted. Your code has many issues not easily solved in a short comment - address the badly formed html and change the php code to only process the specific ID – Professor Abronsius Dec 30 '20 at 12:15
  • @ProfessorAbronsius how do i process the specific id :'(.. – nan Dec 30 '20 at 12:24
  • _"but is it what causes the problen?"_ - Probably not in this case, but that doesn't change the fact that you need to change it :-) Like others have said, there are issues all over here. You need to refactor it all anyway. – M. Eriksson Dec 30 '20 at 12:25
  • @MagnusEriksson ouch 3 – nan Dec 30 '20 at 12:26
  • There are certainly two ways you can do this. Firstly use javascript to process the button click and submit the form with values assigned by javascript to hidden elements ( such as item,cart,qty ) or secondly have multiple forms, one per record with the relevant itemid,cartid and quantity fields – Professor Abronsius Dec 30 '20 at 12:31
  • @ProfessorAbronsius okaay i'll try them.. and then i' ll give up ✌ – nan Dec 30 '20 at 13:02

1 Answers1

0

Perhaps the following might give you an idea of how you might proceed. The PHP that processes the POST request has been designed to work with Prepared Statements but is not yet complete and I will stress that this is not tested! Please look through the html and read the comments which hopefully explain what is going on at that point. Obviously the content of the table ( ie: each table row and cells etc ) will be dynamically generated by db query results - below is static for demo.

The pseudo db processing code here uses mysqli but it looks like you are using PDO so use that as a guide only... look at Prepared Statements here

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
    </head>
    <body>
        <!--
            using a single form to process multiple records requires
            a little more consideration than for a single record. 
            Submitting the form "as-is" leaves you with no way to know
            which particular record PHP should update because they are
            all suitable candidates potentially.
            
            
            
            One method I made reference to was to use a single form with
            just the fields required for processing that are populated 
            by javascript. To that end...
            
            
            * Assign a name to the form for easy identification.
            * remove the `[]` from field names in the form.
            * remove the two hidden fields and assign `dataset` attributes to each button
            
            
            The table below is a loose facsimile of what I deduced the
            original table to look like...more or less.
        -->
        <form method='post' name='update' action='updatecart.php'>
            <table>
                <tr>
                    <th>Update</th>
                    <th>Remove</th>
                    <th>Image & Link</th>
                    <th>Name</th>
                    <th>Quantity</th>
                    <th>Price</th>
                    <th>Total</th>
                </tr>
                <tr>
                    <td><button class="btn" type="button" name="update" data-cartid="23" data-itemid="1">Update</button></td>
                    <td><button class="btn" type="button" name="remove" data-cartid="23" data-itemid="1">Remove</button></td>
                    <td><a href="product_detail.html?itemid=1"><img alt="" src="/photos/banana.jpg" width=100 height=100 /></a></td>
                    <td>Senga-X</td>
                    <td><input type="number" name="quantity" min=1 max=74 value=17 /></td>
                    <td>43</td>
                    <td>93</td>
                </tr>
                <tr>
                    <td><button class="btn" type="button" name="update" data-cartid="69" data-itemid="1">Update</button></td>
                    <td><button class="btn" type="button" name="remove" data-cartid="69" data-itemid="1">Remove</button></td>
                    <td><a href="product_detail.html?itemid=1"><img alt="" src="/photos/apple.jpg" width=100 height=100 /></a></td>
                    <td>Senga-Y</td>
                    <td><input type="number" name="quantity" min=1 max=45 value=10 /></td>
                    <td>35</td>
                    <td>1505</td>
                </tr>
            </table>
            
            
            
            <!-- 
                use only the number of hidden elements as are 
                needed in the sql later for update/delete
            -->
            <input type='hidden' name='cartid' />
            <input type='hidden' name='itemid' />
            <input type='hidden' name='qty' />
            <input type='hidden' name='task' />
        </form>
        <script>
            document.querySelectorAll('button[name="update"],button[name="remove"]').forEach( bttn=>{
                bttn.addEventListener('click',function(e){
                    
                    // stop the form from being submitted conventionally
                    e.preventDefault();
                    
                    // obtain reference to the form
                    let form=document.forms.update;
                        // set values of hidden elements based upon the particular button that was clicked
                        form.cartid.value=this.dataset.cartid;
                        form.itemid.value=this.dataset.itemid;
                        form.qty.value=this.parentNode.parentNode.querySelector('input[name="quantity"]').value;
                        form.task.value=this.name;
                        
                        
                        // send your form with only these values!
                        form.submit();
                });
            });
        </script>
    </body>
</html>

And the PHP to process the request:

<?php

    #updatecart.php

    $dbhost =   'localhost';
    $dbuser =   'root'; 
    $dbpwd  =   'xxx'; 
    $dbname =   'xxx';
    $db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['itemid'], $_POST['cartid'], $_POST['qty'], $_POST['task'] ) ){
        
        $cartid=$_POST['cartid'];
        $itemid=$_POST['itemid'];
        $qty=$_POST['qty'];
        $task=$_POST['task'];
        
        switch($task){
            case 'remove':
                $sql='delete from cart where cart_id=?';
                $stmt=$db->prepare( $sql );
                $stmt->bind_param('s',$cartid);
            break;
            case 'update':
                $sql='update cart set qty=? where cart_id=?';
                $stmt=$db->prepare($sql);
                $stmr->bind_param('ss',$qty,$cartid);
            break;
        }
        
        #etc etc etc
        
        exit();
    }
    
?>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46