Reputation: 43
im trying delete a row on php (i did it) but, always delete the last row, i know why... because everytime i refresh or enter in the page, everytime i got id = "lastrow", my issue is, i dont know why everytime i got the last row id...`$query = "SELECT * FROM ph"; $rs = mysql_query($query);
while ($ph = mysql_fetch_array($rs)) {
echo utf8_encode("
<tr class='etapastext'>
<td >
".$ph['name']."
</td>
<td>
<input type='submit' name='".$ph['id']."' value='Eliminar' >
<input type='hidden' name='name' value='".$ph['id']."'>
</td>
"); }`
then i can access the id of the item i wish to delete, i use this code
$query = "DELETE FROM ph WHERE ph.id = '".$_POST['name']."'";
mysql_query($query);
i'm using $_POST['name']
because is an form, well i dont know if im doing the best way or what im doing bad
i echoed $query
i got DELETE FROM ph WHERE ph.id = '24'
when "24" is always the last row on my table
Upvotes: 0
Views: 63
Reputation: 573
As the definition, there should be unique name for every input type in a single form, What you are doing is giving multiple input types with the
name="name"
so technically when your form will be submitted the last input type with the name='name' with be sent with the form. That's where you are doing wrong. I am not a pro but according to me you have 3 options to delete a row form the database table.
Use a get method to send the value with the url (best way) like
www.xyz.com/delete.php?id=5
(will mess up your code) Use individual form and submit button for each and every input type and most important, your form should start in td
you will create a form on run time with javascript, and based on the selected row values will be filled and form will be submitted, (recommended if you want to use post because it will make your code clean)
hope it will help
Upvotes: 1
Reputation: 2278
You need a form per each html.tr.td
Because you submit the whole result, the last one always overwrite any previous one when form.input.name are same.
Unless you change your input.name to something else
while ($ph = mysql_fetch_array($rs)) {
echo '
<form ....>
<tr class="etapastext">
<td>', $ph['name'], '</td>
<td>
<input type="submit" value="Eliminar">
<input type="hidden" name="name" value="', $ph['id'], '">
</td>
</tr>
</form>
';
)
Upvotes: 0
Reputation: 133
From what I'm seeing so far, your <tr>
tag isn't being closed inside the while()
loop. I would assume that for each array item in $ph
you would want them to each have their own table row.
Fixed code below
while ($ph = mysql_fetch_array($rs)) {
echo utf8_encode("
<tr class='etapastext'>
<td >
".$ph['name']."
</td>
<td>
<input type='submit' name='".$ph['id']."' value='Eliminar' >
<input type='hidden' name='name' value='".$ph['id']."'>
</td>
</tr>
");
}
Hope this helps
Upvotes: 0