Tanmay
Tanmay

Reputation: 3159

Delete button for each mysql result

I am a beginner in PHP. I was trying to create a password manager using PHP and MySQL. But I am having trouble at this point:

<?php
require 'dbconnect.php';

$sql = "SELECT * FROM pmanager";
$result = mysql_query($sql,$con);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
//Views results from existing rows
   for ($j = 0 ; $j < $rows ; ++$j)
    {
        echo 'Account: ' . mysql_result($result,$j,'account') . '<br />';
        echo 'E-mail: ' . mysql_result($result,$j,'email') . '<br />';
        echo 'Username: ' . mysql_result($result,$j,'uname') . '<br />';
        echo 'Password: ' . mysql_result($result,$j,'pword') . '<br />'; ?>
        <form method="post"> <input type="hidden" name="id" value="<?php echo mysql_result($result, $j, 'id'); ?> " /><input type="submit" name="del" value="Delete" /> </form>
 <?php }
if(isset($_POST['del']))
    {
       $sql1 = "DELETE FROM pmanager WHERE id = " . $_POST['id'];
       if(mysql_query($sql1,$con))
       {
          echo 'Deleted';
       }
       else
           echo 'Error: '.mysql_error();
    }
mysql_close($con);
?>

Suppose there are two rows in the table "pmanager" containing two Account (e.g. FB, Twitter). And after executing the code there will be a delete button for each of the accounts. Now what can I do to this button click event so that the desired account can be deleted?

This is my first question in StackOverflow :)

Upvotes: 1

Views: 447

Answers (2)

Mehman Bashirov
Mehman Bashirov

Reputation: 114

echo '<form method="post"> <input type="submit" name="del" value="Delete" /> </form>';

In this part edit the echo code

'<form method="post"><input type="hidden" name="id" value="<?php echo mysql_result($result, $j, 'id'); ?> " /> <input type="submit" name="del" value="Delete" /> </form>';

AND then you can

 if(isset($_POST['del']))
    {
       //What can I do here?
       $id=$_POST['del'];
       $sql='DELETE FROM pmanager WHERE id='.$id
    }

Upvotes: 0

DevZer0
DevZer0

Reputation: 13535

In the most rudimentary forms you can create a hidden field in your mini form with the record id. Then you can capture the id from the delete script and execute the code to delete the record.

<form method="post"> <input type="hidden" name="id" value="<?php echo mysql_result($result, $j, 'id'); ?> " /><input type="submit" name="del" value="Delete" /> </form>

Upvotes: 2

Related Questions