Problems with deleting rown in mysql using php

Rifet Gazdić

i have one problem that i can't resolve.When i make this code and run it, it always delete last row of mysql database.Please help me guys.Ty :D

I had some problems publishing code so u can find it here jsfiddle.net/xhCLz/
under "javascript" box.

<?php
$con=mysqli_connect("localhost","root","","test");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM test_mysql");
$postid1 ="1";
while($row = mysqli_fetch_array($result))
  {
    $ime=$row['name'];
    $prezime=$row['lastname'];
    $id_number=$row['id'];
  echo $ime. " " . $prezime. " " .$id_number. "<form action='' method='post'>

<input type='hidden' name='id_number_send' value='<?php echo $id_number?>'/>
<input type='submit' name='send_value' value='delete' />
</form>";

  }
  if(isset($_POST['send_value']))
{

    $delete_row = mysqli_query($con,"DELETE FROM test_mysql WHERE id='$id_number'");
    echo $id_number;

}
MamaWalter

You don't get id from the POST, instead you use the id assign the last time your loop execute.

You have to get the id of the row you want to delete from the $_POST variable ($_POST['id_number_send']) and sanitise your data before use it in the query to prevent SQL injection (mysqli_real_escape_string).

you should also do your delete before the loop if you want display all rows without the deleted one.

if(isset($_POST['send_value']))
{
    $deleteId = mysqli_real_escape_string($con, $_POST['id_number_send']);
    $delete_row = mysqli_query($con,"DELETE FROM test_mysql WHERE id='$deleteId'");
    echo "ID number: " . $deleteId . " has been deleted.<br><br>";
}
$result = mysqli_query($con,"SELECT * FROM test_mysql");
$postid1 ="1";
while($row = mysqli_fetch_array($result))
  {
    $ime=$row['name'];
    $prezime=$row['lastname'];
    $id_number=$row['id'];
  echo $ime. " " . $prezime. " " .$id_number. "<form action='' method='post'>

<input type='hidden' name='id_number_send' value='$id_number' />
<input type='submit' name='send_value' value='delete' />
</form>";

  }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related