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

时间:2013-05-28 10:57:27

标签: 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中也检查过)。我尝试过一些东西,但没有运气。我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

据我所知,onclick只执行JavaScript代码。您可以尝试将PHP函数放入JavaScript函数中,并从onclick标记

执行此操作