0

Hi guys i have this problem. I have a while loop that shows me the values ​​of a table. Now I need you may delete one of them, if it is wrong. I just can not run this code , I do not understand what is wrong. This is my php where i have the problem.

while( $row = mysql_fetch_array( $res ))
{

echo "<tr>

  <td> ".$row['id']."</td>
  <td> ".$row['val1']."</td>

  <form action='' method='POST'>
  <input type='submit' name='delete' value='".$row['id']."' /></td>
  </form>
  </tr>";

}

if(isset($_POST['delete'])){


$user  = $_POST['delete'];
$delet_query = mysql_query("DELETE FROM table_name WHERE id = '$user' ") or die(mysql_error());

if($delet_query) {
echo "Delete success!";

}
}

Why don't work? Thanks a lot man! I need the user can delete the row.

Andrea php
  • 63
  • 2
  • 8

2 Answers2

1

Your HTML is invalid. There is no <td> before your form:

  <td> ".$row['val1']."</td>

      <----missing <td>
  <form action='' method='POST'>
  <input type='submit' name='delete' value='".$row['id']."' /></td>

So in technical terms, your forms are floating free soemwhere inside the table, within a row, but not within a cell.

Plus, your SQL is vulnerable to injection attacks.

Marc B
  • 356,200
  • 43
  • 426
  • 500
1

It might be better to put your value in a hidden field instead of relying on the submit button's value:

echo "<tr>

        <td> ".$row['id']."</td>
        <td> ".$row['val1']."</td>

        <td>
            <form action='' method='POST'>
                <input type='hidden' name='delete' value='".$row['id']."' />
                <input type='submit' value='".$row['id']."' />
            </form>
        </td>
    </tr>";

Also notice that you were missing and opening <td>, and the corresponding closing </td> was out of place.

mopo922
  • 6,293
  • 3
  • 28
  • 31
  • @Andreaphp have you stepped through to see if `$_POST['delete']` is getting set, if it includes the id, etc? – mopo922 Jan 14 '15 at 16:42
  • I have try to write a echo"test"; but i have see the submit don't enter never in the if(isset($_POST['delete'])){..} @mopo922 – Andrea php Jan 14 '15 at 16:47
  • @Andreaphp maybe try removing the `action=''` as per this thread: http://stackoverflow.com/questions/1131781/is-it-a-good-practice-to-use-an-empty-url-for-a-html-forms-action-attribute-a – mopo922 Jan 14 '15 at 16:51
  • Don't work again, when i click the submit the page refresh and don't do anything @mopo922 – Andrea php Jan 14 '15 at 16:58