Code not deleting the Respective rows from MYSQL table using PHP

44 views Asked by At

The following code displays a table having 4 columns --> id : INT; anytext : TEXT; varcar : VARCHAR, insertdate :TIMESTAMP

<?php
    $sql_r="SELECT * FROM abcd ";
    if($records_r=mysql_query($sql_r))
    {
        echo ' ';
        $k_r=1;
        while($ven_r=@mysql_fetch_assoc($records_r))
        {
           $id_r=$ven_r['id'];
           $anytext_r=$ven_r['anytext'];
           $varcar_r=$ven_r['varcar'];
           $insertdate_r=$ven_r['insertdate'];
           echo"<tr>";                              
           echo "<td>
           <form method='POST' action='example.php'>
               <input type='hidden' name='id_delete2' value='".$id_r."'>
               <button type='submit' class='btn btn-primary'>".$k_r."</button>
           </form><td>";
          echo "<td>".$anytext_r."</td>";
        echo "<td>".$varcar_r."</td>";
        echo "<td>".$insertdate_r."</td>";
        echo"</tr>";
        $k_r+=1;
      }
     }
    ?>

This is the SQL code for deleting a particular row

if(isset($_POST['id_delete2']))
{
    $id_k=$_POST['id_r'];

    {
                    $query="DELETE FROM abcd WHERE id='".$id_k."'";
                    if($query_run=mysql_query($query))
                    {
                            header('Location:exampl.php?suc=1');
                    }
                    else
                    {
                            header('Location:exampl.php?suc=0');
                    }
    }

Please help in finding where is mistake !

2

There are 2 answers

0
Saty On BEST ANSWER

Just change this line of code

$id_k=$_POST['id_r'];

With

$id_k=$_POST['id_delete2'];

Because your field name is id_delete2

<input type='hidden' name='id_delete2' value='".$id_r."'>
                           ^^^^^^^^^^
0
Faiz Rasool On

This is the mistake

$id_k=$_POST['id_delete2'];

But please do not use mysql API use PDO or the Mysqli. To read more about why not use mysql api read here

Why shouldn't I use mysql_* functions in PHP?

Anyway full code will be

if(isset($_POST['id_delete2']))
{
    $id_k=$_POST['id_delete2'];

    {
                    $query="DELETE FROM abcd WHERE id='".$id_k."'";
                    if($query_run=mysql_query($query))
                    {
                            header('Location:exampl.php?suc=1');
                    }
                    else
                    {
                            header('Location:exampl.php?suc=0');
                    }
    }