0

Hello I have the following code displaying a database results, in the 3th TD of the table I would like to insert delete button which will delete the table record of the data which is next to the button, what should be the code in the 3th TD of the tabe for the delete button ?

<?php
$con=mysqli_connect("localhost","table","password","database");
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM recetas_galletas");
echo "<table border='1'>
<tr>
    <th>Title</th>
    <th>Description</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
    echo "<tr>";
    echo "<td>" . $row['title'] . "</td>";
    echo "<td>" . $row['description'] . "</td>";
    echo "<td>" . DELETE BUTTON "</td>";
    echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Avdhesh
  • 15
  • 5
Vladimir Vasilev
  • 19
  • 1
  • 1
  • 6

3 Answers3

1

There are several ways to archive this, first and and most important is that you need a field on your database table where you can identify the record you want to delete, for example a primary key in form of an ID or a unique key.

You can do this by creating a link with a text to a delete.php page or you can use JQuery and AJAX or you can use a inner form.

You will also want to have only authorized users to use those pages so you will need a login page with session as well.

You can see here an example of login page with sessions.

The simplest one is a link to the delete page, see example here:

<?php
$con = mysqli_connect("localhost","table","password","database");
// Check connection
if (mysqli_connect_errno())
{
    die("Failed to connect to MySQL: " . mysqli_connect_error());
}

if (!$result = mysqli_query($con,"SELECT * FROM recetas_galletas"))
{
    die("Error: " . mysqli_error($con));
}
?>
<table border='1'>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['description']; ?></td>
<td><a href="delete.php?id=<?php echo $row['id']; ?>">Delete</a></td>
</tr>
<?php
}
mysqli_close($con);
?>
</table>

Then on your delete page you would have something like this:

<?php
// Your database info
$db_host = '';
$db_user = '';
$db_pass = '';
$db_name = '';

if (!isset($_GET['id']))
{
    echo 'No ID was given...';
    exit;
}

$con = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($con->connect_error)
{
    die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}

$sql = "DELETE FROM recetas_galletas WHERE id = ?";
if (!$result = $con->prepare($sql))
{
    die('Query failed: (' . $con->errno . ') ' . $con->error);
}

if (!$result->bind_param('i', $_GET['id']))
{
    die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}

if (!$result->execute())
{
    die('Execute failed: (' . $result->errno . ') ' . $result->error);
}

if ($result->affected_rows > 0)
{
    echo "The ID was deleted with success.";
}
else
{
    echo "Couldn't delete the ID.";
}
$result->close();
$con->close();
Community
  • 1
  • 1
Prix
  • 19,417
  • 15
  • 73
  • 132
  • `only authorized users to use those pages ` **Absolutely**!! Otherwise search engines will delete all your entries! I would strongly suggest against using any form of GET requests for delete actions. – ComFreek Sep 24 '13 at 18:27
  • There is nothing wrong with using GET as long you're doing it properly as in any other thing on PHP, it all comes down to personal options of the user. Some will use AJAX with post with the inner page change some will use a form, I am merely giving him an example of how to archive what he wants with the simplest way. Glad you or whoever down voted it found it worth doing so. – Prix Sep 24 '13 at 18:35
  • it worked excellent, this page will be inside restricted area on the server. – Vladimir Vasilev Sep 24 '13 at 18:36
  • @VladimirVasilev it would still be better if you properly use session and define access level to your users and permission so others don't delete or have access to what they should not have. – Prix Sep 24 '13 at 18:37
  • I didn't downvote! I just wanted to warn the OP or other readers reaching this answer. As I said in another comment, you might install a local search engine later on and what do you do if you forgot these links? All entries will be deleted. – ComFreek Sep 24 '13 at 18:38
  • @ComFreek the warn was not directed only to your person and yes that's exactly why I point that its better if he uses session to prevent unwanted things from accessing the page. – Prix Sep 24 '13 at 18:39
  • Yeah I will use also Session for the administration area. Thanks for the advice ! – Vladimir Vasilev Sep 24 '13 at 18:54
1

You can make a link that passes the id to another php page which preforms the delete. So the link will be like :

echo "<td><a href='http://www.site.com/delete.php?id=" . $row['id'] . "'></td>";

then in your delete.php :

if (is_int($_GET["id"]) {
    $query = "DELETE FROM recetas_galletas WHERE id = " . $_GET["id"];
    $result = mysqli_query($con, $query);
    // Check the result and post confirm message
}

This is a very simple way of doing it but it might not be the best for you .If you didn't verify the user of this page, any one could manipulate this code easily and delete any row of the table.

Other ways could be navigating to the same page and do the same process in the same page or you could use ajax but this is another issue.

Hope this helps and excuse my English.

A.Essam
  • 1,094
  • 8
  • 15
  • Don't do it using links! Search engines will delete all items. Even if your page is inaccessible from outside, you might install a local search engine later on. – ComFreek Sep 24 '13 at 18:35
  • I agree with you, It can only be used in closed sessions with no search engines in the site. **"This is a very simple way of doing it but it might not be the best for you"** – A.Essam Sep 24 '13 at 18:42
1
echo "
<form action='user.php' method='post'>
        <table cellpadding='2' cellspacing='2' border='2' >
        <tr>
            <td>Id</td>
            <td>Name</td>
            <td>Gender</td>
            <td>Action</td>
        </tr>
     ";

$select = "select * from user";
$result = mysqli_query($con,$select);
while($r = mysqli_fetch_row($result))
{
    echo "
    <tr>
        <td>$r[0]</td>
        <td>$r[1]</td>
        <td>$r[2]</td>
        <td><input type='submit' value='Delete  $r[0]' style='width:53px;' name='submit' ></td>
    </tr>
    ";
}
echo "
        </table>
        </form>
     ";


if ($_POST['submit'])
{
    $id = $_POST['submit'];
    $id = end(explode(" ",$id));

    $delete = "delete from user where id=$id";
    mysqli_query($con,$delete);
    header("Location:user.php");
}
?>
Bjjs JKD
  • 11
  • 1
  • I sure hope that the first, second and third values in the database are ID, name and gender! Also, be careful; you're leaving yourself wide open for SQL injection in your delete statement. – Chris Forrence May 31 '17 at 15:34