0

My aim is for a user to click a button within a row to delete that row within the database.

The button is declared as so:

<td><button class="btn btn-default" onclick="removeStudent()" button id= <?php echo $productDetails["studentID"]; ?> type="button">Delete</button></td>            

The remove function is as follows:

<script>                    
                function removeStudent() {
                    $id = window.event.target.id.toString();
                    $sql = "DELETE FROM tableStudent WHERE studentID= '$id'" ;

                    if (mysqli_query($connection, $sql)) {
                        echo "Record deleted";
                    } else {
                        echo "Error deleting";
                    }

                }
</script>

The webpage is connected to the database, and variable names are correct and working within other functions. Just delete function not working. Any help would be much appreciated.

nivlem
  • 39
  • 1
  • ^ Text to start with. – u_mulder Dec 09 '16 at 20:12
  • PHP and javascript dont work together. Javascript needs to send a request (AJAX) to the server where the PHP will execute and return the response. Additionally `DELETE FROM tableStudent WHERE studentID= '$id'` would open you to SQL injections. Use parameterized queries. – chris85 Dec 09 '16 at 20:12

1 Answers1

1

It looks like you are mixing javascript and PHP here. I'm not sure you understand how PHP works. Any PHP code on your page is run before the page is ever sent to the user, so you can't put PHP stuff inside javascript function (well you can, but it will be run and turned into plaintext before the javascript is ever even read by the user's browser.) So your line where you go $id = window.event.target.id.toString(); won't work, since you are trying to set a PHP variable using javascript. Actually none of that code will do anything, since its not inside a <?php block. It will just cause errors in the browser console because it is invalid javascript code.

You need to make your javascript function make an ajax call to another PHP page, which actually does the delete

Mogzol
  • 1,405
  • 1
  • 12
  • 18