php - 从按钮调用 PHP 函数以从表中删除行

标签 php function button html-table

我在 PHP 页面中有以下代码,用于显示表中的数据。在最后一列中,我有一个删除按钮,它调用一个函数来从表中删除相应的行:

    // Print data from db
    $result = mysql_query("SELECT * FROM questions");
    echo "<table border='1' align='center'>
    <tr>
    <th>ID</th>
    <th>Multiple Choice Question</th>
    <th>Correct answer</th>
    <th>The Tip You Give</th>
    <th>Edit Question</th>
    <th>Delete Question</th>
    </tr>";
    while($row = mysql_fetch_array($result))
    {
        echo "<tr>";
        echo "<td align='center'>" . $row['ID'] . "</td>";
        echo "<td>" . $row['Question'] . "</td>";
        echo "<td align='center'>" . $row['Answer'] . "</td>";
        echo "<td>" . $row['Help'] . "</td>";
        echo "<td align='center'><button type='button' onclick='edit_question()'><img src='images/Edit.png'></button></td>";
        echo "<td align='center'><button type='button' onclick='delete_question($row)'><img src='images/delete.png'></button></td>";
        echo "</tr>";
    }
    echo "</table>";

函数如下:

    <script>
    function delete_question(int $row_id)
    {
       var r=confirm("Are you sure you want to delete this question?");
       if (r==true)
       {
          alert('<?php 
          $con=mysql_connect("localhost","stesia","stesia","stesia");
          // Check connection
          if (mysql_errno())
          {
             echo "Failed to connect to MySQL: " . mysql_error();
          }
          mysql_query($con,"DELETE FROM questions WHERE ID='".$row_id."'");
          echo "You want to delete the " . $row_id['ID'] . " question!";
          echo "Question deleted!";
          mysql_close($con);
          ?>');
       }
       else
       {
          alert("Question not deleted!");
       }
    }
    </script>

问题是该函数被调用并显示消息,但该行没有被删除(也在 mysql 中检查过)。我尝试过一些事情但没有运气。我在这里做错了什么?

最佳答案

您无法在客户端执行此操作。您应该向服务器(PHP-)端发送 AJAX 请求来处理删除。

您可以在此处找到相关信息(虽然这些信息并未显示最佳实践,但有助于理解概念): PHP - AJAX and MySQL

关于php - 从按钮调用 PHP 函数以从表中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16790312/

相关文章:

javascript - 仅使用 Electron (Atom shell) 和 PHP+mysql 服务器的身份验证表单

php - 优化 CI 中的 MySQL 查询

sql - 具有新功能的 Asterisk

javascript - URL 更改后更改按钮的状态

css - 如何解决为网页创建带有动态文本的图形按钮的问题

PHPExcel 将 XLS 转换为具有特殊字符的 CSV

php - Pyrocms,在 where 子句上流

javascript - 如何缓存文本区域?

c - 自定义drawRect()函数中是否存在错误或我的错误?

apache-flex - 在 Spark 按钮皮肤上添加图标