I have the following loop, which creates a list from a database:
for ($i=0;$i<count($tutor_subj);$i++){
$query_tutors = "SELECT level, subject FROM level, subject WHERE level.id = '$tutor_lvl[$i]' AND subject.id = '$tutor_subj[$i]'";
$result_t = mysqli_query($db_conx, $query_tutors);
while($m = mysqli_fetch_array($result_t)){
echo $m['level']." ".$m['subject']." ".$tutor_top[$i]."<div style='float:right; padding-right:5px;'><a href='#'><img src='images/remove_btn.png' onclick='removeSubj'></a></div></br>";
}
}
?>
As you can see I'm adding a 'remove' button in the html after each entry, and I want to use this button to allow the users to delete that particular row of data from the database if they choose.
My question is how can I link the row from this while loop to the button being generated at the end of each line (so that the appropriate entry is deleted in the DB)?
PS - I havent written the javascript/jquery function removeSubj yet because I'm stuck, hence am not including that
Add an unique identifier to onclick='removeSubj'
so that when it is called, you can determine what you would want to delete. You could use something like onclick='removeSubj("unique_identifier")'
. Replace that unique_identifier with something that is always unique for every row in your database (for example an id-field).
You can then use this value in your javascript function, and finally in your server-side script, to delete the correct row.
Let me give you and example to buttress @sumurai8s' point because i had the same issue before i read his answer.
assuming this is the item you intend to loop (i.e you have dynamically generated this from your php/database loop)
<div class="media-body media-right">
<span onclick="delete(<?php echo $fromDb['id']; ?>);" class="icon icon-trash-o icon-3x text-blood pull-lg-right"></span>
</div>
This is what your java script should be
//delete
function delete(I) {
// delete methodology
var id_to_be_deleted = I;
var formData = new FormData();
formData.append("id_to_be_deleted", id_to_be_deleted);
$.ajax({
type: "POST",
url: "/delete.php",
contentType: false,
processData: false,
//contentType: "application/json; charset=utf-8",
dataType: "json",
data : formData,
success: function()
{
alert('successs');
}
});
}
And delete.php should be
<?php
if ($_POST['id_to_be_deleted']) {
$delete = $_POST['id_to_be_deleted'];
//do db delete query here i.e DELETE FROM table_name WHERE id='$id_to_be_deleted'
...
}
if you don't do it this way you might be experiencing your DELETE ACTION being fired twice.
Don't thank me, thank @sumurai8 for waking me up from my slumber ;)
Happy coding.