delete data from sql database from a link without a form

时间:2018-02-03 11:27:55

标签: php html mysql

I am trying to delete data from an sql database with a link, but I am not using a form. How would I go about getting the ID...

<?php
    $sql = "SELECT id, name, imgpath, price FROM tracylynn";
    $result = $db->query ( $sql );

    if ($result->num_rows > 0) {
        ?>
        <table class="table">
            <tr>
            <td class="td" style="font-weight: bold;"><p class="text-primary">ID: </p></td>
            <td class="td" style="font-weight: bold;"><p class="text-primary">Name: </p></td>
            <td class="td" style="font-weight: bold;"><p class="text-primary">Price: </p></td>
        <?php
        while ( $row = $result->fetch_assoc () ) {
            ?>
                <tr>
                <td class="td"><?php echo '<p class="text-secondary">'.$row["id"].'</p>';?></td>
                <td class="td"><?php echo '<p class="text-secondary">'.$row["name"].'</p>'?></td>
                <td class="td"><?php echo '<p class="text-secondary">'.$row["price"].'</p>'?></td>
                <td class="td" style="text-align: center;"><a href="" class="btn btn-default btn-danger" >Delete</a>
            <?php
        }
        ?>
        </table>
        <?php
    }
    ?>

2 个答案:

答案 0 :(得分:1)

您的href标记看起来像

<a href="demo.php?id=<?php echo $row["id"]; ?>" class="btn btn-default btn-danger" >Delete</a>

现在创建一个文件demo.php并执行此操作

  if (isset($_GET['id'])) {
    $id=$_GET['id'];
// now your delete query or as you want

}

这只是演示。您可以在解决安全问题后实际处理删除请求。

答案 1 :(得分:1)

在这里你可以捕获id并删除记录。

if(!empty($_GET['id']) && $_GET['action'] == 'delete'){
        $id = $_GET['id'];
        $deleteRow = "DELETE FROM tracylynn WHERE id = '$id'";
        $success = $db->query ( $deleteRow );
        if($success){
           $url = $_SERVER['PHP_SELF'];
           header("LOCATION: $url");
        }
    }

在这里你可以将id传递给目标页面

<td class="td" style="text-align: center;"><a href="<?php echo $_SERVER['PHP_SELF']."?action=delete&id=".$row["id"]; ?>" class="btn btn-default btn-danger" >Delete</a>