簡體   English   中英

使用php和sql從數據庫中刪除數據

[英]Delete data from database using php and sql

所以我有一個看起來像這樣的 php 頁面

在此處輸入圖片說明

<?php
    echo "<table border='1' width= 300px >
    <tr>
        <th>Friend Names</th>
        <th>Remove Friends</th>
    </tr>";
    
    while($row = mysqli_fetch_assoc($result2))
    {
        $friend_id_got = $row['friend_id2'];
    
        $query3 = "SELECT profile_name 
                    from friends 
                    where friend_id = '$friend_id_got' ";
        $result3 = $conn->query($query3);
        $final3 = mysqli_fetch_assoc($result3);

        echo "<tr>";
            echo "<td>" . $final3['profile_name'] . "</td>";
        echo "<td>" 
    ?>
        <form action="friendlist.php" method= "POST">
            <button id="add-friend-btn" type= 'submit' name = 'submit'>Unfriend</button>
        </form>
    <?php
  
        "</td>";
        echo "</tr>";
    }

    echo "</table>";

當我按下按鈕時,我需要相應的名稱才能刪除它。 我面臨的唯一問題是如何獲取與按鈕對應的名稱。 我認為我們需要以某種方式將按鈕和名稱聯系起來,因此當按下特定按鈕時,我會得到相應的名稱

從問題和評論,再看一眼你的代碼,當你點擊按鈕時,你可能實際上需要將兩條數據提交給服務器:

  1. 響應請求應采取的行動(即取消好友關系)

  2. 被取消好友的人的ID

為此,您可以在表單中添加一些隱藏字段。 這些對用戶是不可見的,但在提交表單時在$_POST數據中對 PHP 可用。

像這樣的東西:

<form action="friendlist.php" method= "POST">
  <input type="hidden" name="unfriend_id" value="<?=$friend_id_got ?>" />
  <input type="hidden" name="action" value="unfriend" />
  <button id="add-friend-btn" type="submit" name= "submit">Unfriend</button>
</form>

繼@ADyson 的評論之后:

<form action="friendlist.php" method= "POST">
    <input type="hidden" name="cancel_id" value="<?=$friend_id_got ?>" />
    <button id="add-friend-btn" type="submit" name="submit">Unfriend</button>
</form>

通過在表單中​​包含一個隱藏字段,您可以存儲更多信息。

您可以看到我在隱藏字段的值中存儲了您取消好友的朋友的 ID,因此當提交表單(單擊按鈕)時,您將可以訪問 POST 數據中的“cancel_id” ,其中顯然包含要取消好友的好友的 ID。

<!-- On top of your page -->
<?php
 if(isset($_GET['friend_id'])){
     $fid = $_GET['friend_id'];
     $deleteAction = mysqli_query($your_connection_variable,"DELETE from friends where id='$fid'");
     header('Location: ' . $_SERVER['HTTP_REFERER']);
 }


?>

<!-- ends -->

<table border='1' width=300px>
    <tr>
        <th>Friend Names</th>
        <th>Remove Friends</th>
    </tr>

    <?php
    while($row = mysqli_fetch_assoc($result2))
    {
        $friend_id_got = $row['friend_id2'];
    
        $query3 = "SELECT profile_name 
                    from friends 
                    where friend_id = '$friend_id_got' ";
        $result3 = $conn->query($query3);
        $final3 = mysqli_fetch_assoc($result3);    
    ?>
    <tr>
        <td><?=$final3['profile_name']?></td>
        <td><a href="your_current_page_name.php?friend_id=<?php echo $final3['id'] ?>">Unfriend</a></td>
        </td>
    </tr>
    <?php } ?>
</table>

無需添加表單來刪除特定 id 只需傳遞該朋友的 id 並在同一頁面上點擊獲取請求(頁面可能會有所不同,根據您的需要)。 現在獲取 id 並執行與該行的刪除查詢對應

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM