Fiorucci Fiorucci - 2 years ago 63
HTML Question

MySQL is deleting the last row of html table / Code Igniter

This is my controller, that i use to send the row to the model:

function excluir(){
$codcliente = $this->input->post('codcliente');

my model:

function excluirCliente($codcliente){
$this->db->delete('cliente', array('codcliente' => $codcliente));

my table (view):

<form action="#" method="POST" id="form">
<div style="float: left;">
<input type="button" onclick="cadastro();" value="Novo cliente" name="botao" class="btn btn-primary">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<th> </th>
foreach ($records as $row){ ?>
<td><input name="codcliente" id="codcliente" value="<?php echo $row->codcliente ?>"></td>
<td><?php echo $row->nome ?></td>
<td><?php echo $row->cidade ?></td>
<td><?php echo ($row->telefone == null) ? "-" : $row->telefone ?></td>
<td><center><input type="button" onclick="excluir();" value="Delete"></td>
<?php } ?>

and my JS:

function excluir(){
document.forms['form'].action = "<?php base_url();?>excluir";


its working fine, but the code is deleting my last row in relation with the table on html. i used the order by too see whats beeing deleted, and it works the same...

i dont know what's wrong

Answer Source

Your problem is that you are using the same form name name="codcliente" for all your rows and then submitting the whole form when you delete. The server sees the last value for codcliente which will be your last row and hence deletes it.

To fix, I suggest you use unique form names for each row for all your row fields. Eg. Instead of name="codcliente" use name="codcliente_<?php echo $row->id ?>". And then when you post to the server to delete, use a data-name=<?php echo $row->codcliente ?> on the delete button and in the onClick handler use $(this).data('name') to get the unique name of the field and post that to the server. I suggest you use ids instead of names as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download