2

I have the following code inside PHP page that displays data from a table. In the last column I have a delete button that calls a function to delete the corresponding row from the table:

    // 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>";

the function is the following:

    <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>

The problem is that the function is called and displays the messages, but the row is not deleted (checked that in mysql also). I have tried some things but no luck. What am I doing wrong here?

1
  • 2
    javascript is no PHP. do some ajax request. Commented May 28, 2013 at 10:58

2 Answers 2

2

You cannot do this on client side. You should send an AJAX request to the server (PHP-) side to handle the deletion.

You can find related information here (though these are not showing the best practices, but it helps understanding the concepts): PHP - AJAX and MySQL

Sign up to request clarification or add additional context in comments.

Comments

0

As far as i know onclick only executes JavaScript Code. You could try to put your PHP function into a JavaScript function and execute this from the onclick tag

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.