Passing a value through Button to Php function
You need both the action
(edit/delete) and the row id
. Unfortunately, without some JS the button will only post one value.
You can create a new form for each row, add in a hidden element. For example:
<?php while ($row = mysql_fetch_array($query)) : ?>
<tr>
<!-- other cells -->
<td>
<form method="post" action="">
<input type="submit" name="action" value="Edit"/>
<input type="submit" name="action" value="Update"/>
<input type="hidden" name="id" value="<?php echo $row['id']; ?>"/>
</form>
</td>
</tr>
<?php endwhile; ?>
Then after posting it you can just check for the action
and id
if ($_POST['action'] && $_POST['id']) {
if ($_POST['action'] == 'Edit') {
// edit the post with $_POST['id']
}
}
You can do it one of two ways.
jQuery and AJAX
For each <tr>
, everywhere there is a delete button,
<a href="#" data-id="<?php echo $value; ?>" class="delete-row">Delete</a>
Script at the bottom:
//Include jQuery here
<script language="javascript">
$('.delete-row').click(function (event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax({
url: "url/to/delete",
method: "POST",
cache: false,
data: { id: id },
success: function (html) {
$(this).parent().parent().remove();
});
});
});
</script>
This puts the ID of the row into the <a href>
itself using data
and uses jQuery to send out an AJAX call to delete the record. If the delete is successful, it removes the row from the table.
Old-School Button
For each <tr>
, everywhere there is a Delete button,
<form method="POST" action="url/to/delete">
<input type="hidden" name="id" value="<?php echo $value; ?>" />
<input type="submit" value="Delete" />
</form>
This is the old-school way to do it, where the hidden field is how the backend knows which row to delete.
On the backend, you still use $_POST['id'];
to get the ID of the record to remove. In the above examples, $value
is the ID for each row, and is most likely something like $row['id']
when it is coming from a foreach()
.
Use a hidden input (e.g.<input type="hidden" value="your_value_here">
)