Search code examples
phphtmlmysqlhtml-tabledelete-row

Next row or id gets deleted from table and database


I have a table of chapters for which I have a delete button for each one. When I am clicking on delete button if the table has more records further the last row of the table gets deleted or the id of row getting pass to the database is wrong.

<!doctype html>
<html>
<head>
<title>Files</title>
</head>
<body>

<form method="post" action="deleteFiles.php" enctype="multipart/form-data">

<style>
td {
    text-align: center;
    border: 1px solid black;
    border-collapse: collapse;
}
</style>

Select rank :
<select name="type" id="type" onchange="this.form.submit()"> 

<?php if(isset($_POST['type']))
{ ?>
<option value="1"  <?php echo($_POST['type']==1?"selected":"");?>>SSgt</option> 

<option value="2"  <?php echo($_POST['type']==2?"selected":"");?>>TSgt</option> 
<option value="3" <?php echo($_POST['type']==3?"selected":"");?>>MSgt</option>
</select>
<br><br>
<?php
}
    else 
    {
    ?>
    <option value="1">SSgt</option> 
<option value="2">TSgt</option> 
<option value="3">MSgt</option> 
</select>
<br><br>
    <?php
    }
    ?>

<table id="example" style="width:60%">
    <tr>
    <th><font size="5">Files</font></th>
  </tr>

<?php



?>

<?php

ini_set('display_errors', 1); 
error_reporting(1); 
ini_set('error_reporting', E_ALL); 

    $dbh = new PDO('mysql:host=174;dbname=airman', 'airman', 'airma'); 


if(isset($_POST['action'])) {


     $stmt = $dbh->prepare("DELETE FROM `files` WHERE `id`= " . $_POST['id']); 

    $stmt->execute(); 
    $result = $stmt->fetch(PDO::FETCH_ASSOC); 

        if(count($result) > 0)
        {
          echo 'row deleted';
        }
        else{
            echo 'row could not delete';    
        }
    }


if(isset($_POST['type']))
{
    $stmt = $dbh->prepare("SELECT * FROM files where type = :type"); 
    $stmt->bindParam("type", $_POST['type']);
    $stmt->execute(); 
    $results = $stmt->fetchall(PDO::FETCH_ASSOC);

}
    else{
        $stmt = $dbh->prepare("SELECT * FROM files"); 
    $stmt->execute(); 
    $results = $stmt->fetchall(PDO::FETCH_ASSOC);

}

    foreach($results as $file)

    {
    ?>
     <tr>
    <td><?php echo $file['title'];?></td>
    <td><input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">
        <input type="submit" id="<?php echo $chap['id']?>" name="edit"  value="Edit">
    <input type="hidden" name="id" value="<?php echo $file['id']?>" />

  </tr> 
    <?php
}
?>
</table>

</body>

</form>
</html>
<?php
?>

EDIT:

    <!doctype html>
<html>
<head>
<title>Video Files</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>

    $('#form').submit(function(ev) {

        $('<input type="hidden">').attr({ name: 'type', value: $("select[name='type']").val() }).appendTo($(event.currentTarget));
    }

    </script>
<form id="form" method="post" action="deleteVideoFiles.php" enctype="multipart/form-data">

<style>
td {
    text-align: center;
    border: 1px solid black;
    border-collapse: collapse;
}
</style>


    <br><br><br><br>
Select rank :
<select name="type" id="type" onchange="this.form.submit()">

<?php if(isset($_POST['type']))
{
  /*  session_start();

    $_SESSION['vidType'] = $_POST['type'];*/

    ?>
    <option value="">Select rank...</option>
    <option value="1"  <?php echo($_POST['type']==1?"selected":"");?>>SSgt</option>

    <option value="2"  <?php echo($_POST['type']==2?"selected":"");?>>TSgt</option>
    <option value="3" <?php echo($_POST['type']==3?"selected":"");?>>MSgt</option>
    </select>
    <br><br>
    <?php
}
else
{
/*    session_start();

    $_SESSION['vidType'] = $_POST['type'];*/

    ?>
    <option value="">Select rank...</option>
    <option value="1">SSgt</option>
    <option value="2">TSgt</option>
    <option value="3">MSgt</option>
    </select>
    <br><br>
    <?php
}
    ?>

<table id="example" style="width:80%">
    <tr>
        <th><font size="5">Video Files</font></th>
    </tr>

    <?php

    ?>

    <?php

    ini_set('display_errors', 1);
    error_reporting(1);
    ini_set('error_reporting', E_ALL);

    $dbh = new PDO('mysql:host=174.75.54;dbname=handbook', 'airman', 'airman12345');
  //  $dbh = new PDO('mysql:host=localhost;dbname=handbook', 'siddhi', 'siddhi');

    if(isset($_POST['action'])) {

        $stmt = $dbh->prepare("DELETE FROM `videos` WHERE `id`= :id");
        $stmt->bindParam("id", $_POST['id']);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if(count($result) < 0)
        {
            echo 'row could not delete';
        }
    }

    if(isset($_POST['type']))
    {

        if(!empty($_POST['type']))

        {

            $stmt = $dbh->prepare("SELECT * FROM `videos` where type = :type");
            $stmt->bindParam("type", $_POST['type']);
            $stmt->execute();
            $results = $stmt->fetchall(PDO::FETCH_ASSOC);
            if(count($results) == 0)
            {
                echo 'No records available.';
            }
        }
        else{

            echo 'empty type';
            $stmt = $dbh->prepare("SELECT * FROM `videos`");
            $stmt->execute();
            $results = $stmt->fetchall(PDO::FETCH_ASSOC);
            if(count($results) == 0)
            {
                echo 'No records available.';
            }

        }
    }
  /*  elseif(!empty($_SESSION['vidType'])){

        echo $_SESSION['vidType'];
        echo $_POST['type'];

            $stmt = $dbh->prepare("SELECT * FROM `videos` where type = :type");
            $stmt->bindParam("type", $_SESSION['vidType']);
            $stmt->execute();
            $results = $stmt->fetchall(PDO::FETCH_ASSOC);
            if(count($results) == 0)
            {
                echo 'No records available.';
            }
    }*/

    else{

            $stmt = $dbh->prepare("SELECT * FROM `videos`");
            $stmt->execute();
            $results = $stmt->fetchall(PDO::FETCH_ASSOC);
            if(count($results) == 0)
            {
                echo 'No records available.';
            }
    }
    foreach($results as $file)

    {
        ?>
        <tr>
            <td><?php echo $file['title'];?></td>
            <td>
          <form method="post" action="deleteVideoFiles.php" enctype="multipart/form-data">

              <input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete"><br>
                    <input type="hidden" name="id" value="<?php echo $file['id']?>"/>
             </form> <!-- notice how we built different form for every id-->
            </td>
        </tr>
        <?php
    }
    ?>
</table>

</body>

</form>
</html>
<?php
?>

I am sending the id of chapter in for each loop, What is the problem here? Please help thank you..


Solution

  • That is because building the form element this way is going to result for many id inputs inside the same form. something like this

    <form>
        <input name="id" value="1">
        <input name="id" value="2">
    </form>
    

    on your server code the php will set $_POST['id'] to the last one which in this case 2. that is why when press delete button and submit the form you delete the next , or last id you have built in your form

    If you need your code work the way you want you have to put every id in different form element, Or you will need some javascript work.

    I prefer building different form for each record. replace that code

    foreach($results as $file)
    {
    ?>
    <tr>
        <td><?php echo $file['title'];?></td>
        <td><input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">
        <input type="submit" id="<?php echo $chap['id']?>" name="edit"  value="Edit">
        <input type="hidden" name="id" value="<?php echo $file['id']?>" />
    </tr> 
    <?php
        }
    ?>
    

    with something like this

    foreach($results as $file)
    {
    ?>
    <tr>
        <td><?php echo $file['title'];?></td>
        <td>
            <form method="post" action="deleteFiles.php" enctype="multipart/form-data">
                <input type="submit" id="<?php echo $file['id']?>" name="action" value="Delete">
                <input type="submit" id="<?php echo $chap['id']?>" name="edit"  value="Edit">
                <input type="hidden" name="id" value="<?php echo $file['id']?>" />
            </form> <!-- notice how we built different form for every id-->
        </td>
    </tr> 
    <?php
        }
    ?>
    

    Another note :

    $stmt = $dbh->prepare("DELETE FROM `files` WHERE `id`= " . $_POST['id']);
    

    using prepared statements this way makes you still vulnerable to SQL injection.


    EDIT(reaction to comments) to send another input along with the delete forms to the PHP server. you can use JavaScript for that.

    1- add that class deleteForm to the delete forms so we can catch those forms and bind to only them.

    <form method="post" class="deleteForm" action="deleteVideoFiles.php" enctype="multipart/form-data">
    

    2- edit that script tag in your document

    <script>
        $(function (){
            $('form.deleteForm').submit(function(ev) {
                $('<input type="hidden">').attr({ name: 'type', value: $("select[name='type']").val() }).appendTo($(ev.currentTarget));
            });
        })
    
    </script>