【问题标题】:Delete data from database using php and sql使用php和sql从数据库中删除数据
【发布时间】:2021-12-08 02:59:57
【问题描述】:

所以我有一个看起来像这样的 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>";

当我按下按钮时,我需要相应的名称来删除它。我面临的唯一问题是如何获得与按钮对应的名称。 我认为我们需要以某种方式关联按钮和名称,所以当按下特定按钮时,我会得到相应的名称

【问题讨论】:

  • 只需在包含 ID 的表单中添加一个隐藏字段(我希望来自 $friend_id_got)。然后,当您提交表单时,它会在 $_POST 数据中可用
  • 你的意思是像一个输入字段?好的,但是如何获取按下的相应按钮的名称。
  • 我的意思是一个隐藏字段(developer.mozilla.org/en-US/docs/Web/HTML/Element/input/hidden)。 But how do I get the name of which corresponding button is pressed...你不需要按钮的名称,你需要被取消好友的人的 ID。这就是隐藏字段将提供的。这就是您将在查询中用于更新数据库的内容。当您说“按钮的名称”时,您真的是指“表明要执行的操作是“取消好友”操作的东西吗?如果是这样,那么另一个隐藏字段就可以了。
  • 良好的代码缩进将帮助我们阅读代码,更重要的是它将帮助您调试您的代码 Take a quick look at a coding standard 为您自己的利益。您可能会被要求在几周/几个月内修改此代码,最后您会感谢我的。
  • 您的脚本对SQL Injection Attack 开放。即使是if you are escaping inputs, its not safe!,您也应该始终在MYSQLI_PDO API 中使用prepared parameterized statements,而不是将用户提供的值连接到查询中。永远不要相信任何用户输入!

标签: php html sql forms mysqli


【解决方案1】:

继@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 存储在隐藏字段的值中,因此当提交表单(单击按钮)时,您将可以访问“cancel_id” POST 数据,显然会包含要取消好友的好友的 ID。

【讨论】:

    【解决方案2】:

    从问题和 cmets 看,您的代码听起来好像您实际上可能需要在单击按钮时将两条数据提交到服务器:

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 2018-02-05
      • 1970-01-01
      • 2014-05-09
      相关资源
      最近更新 更多