2

我在显示表格数据的 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中检查过)。我尝试了一些东西,但没有运气。我在这里做错了什么?

4

2 回答 2

2

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

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

于 2013-05-28T11:04:07.900 回答
0

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

于 2013-05-28T11:01:12.907 回答