user6582683 user6582683 - 1 month ago 9
PHP Question

Delete and redirect to the page in php

I am trying to delete the entry in php and redirect the page in php.
I need to redirect the page based on condition as

header("Location: report2.php?region=$region");
after deletion page doesnt get redirected to
header("Location: report2.php?region=$region");

It doesnt delete also. It only redirects to report2.php?delete_id=103
Here is the code

?php
//Give your mysql username password and database name
include_once "db.php";
if(isset($_REQUEST['region']))
{
$region=$_REQUEST['region'];

//connection to the database


$qresult = mysql_query("SELECT * FROM registration where region='".$region."'");

echo "<h1>Registration Details of $region Region.</h1>";
if (mysql_num_rows($qresult) == 0) {
echo "<h3 style=color:#0000cc;text-align:center;>No Registrations Done..!</h3>";
} else {


echo "<table border='1' cellpadding='0' cellspacing='0' class='reports'>";

echo "<tr>" .
"<td style='background: #f1f1f1; font-weight: bold;text-align:center;'>Registration Number</td>" .
"<td style='background: #f1f1f1; font-weight: bold;text-align:center;'>Name</td>" .
"</tr>";

while($row = mysql_fetch_assoc($qresult)) {
echo "<tr>" .
"<td style=text-align:center;>" . $row['id'] . "</td>" .

"<td style=text-align:center;>". $row['name'] . "</td>";


?>

<td><a href="javascript:delete_id(<?php echo $row['id']; ?>)"><img src="images/delete21.png" alt="Delete" /></a></td>


</tr>
<?php
}
}}
?>
</table>
<?php
if(isset($_GET['delete_id']))
{
$sql_query="DELETE FROM registration WHERE id=".$_GET['delete_id'];
mysql_query($sql_query);

header("Location: report2.php?region=$region");
exit;
}

?>

Answer

I think your problem is based on bad formatting, therefor you didn't notice that your if doesn't close before the next if-statement, which I don't think you intended.

Here is your fixed and formatted code:

<?php

  include_once "db.php";
  if(isset($_REQUEST['region'])) 
  {
    $region=$_REQUEST['region'];

    $sql_query="SELECT * FROM registration where region='".$region."' ";
    $result_set=mysql_query($sql_query);
  }
  if(isset($_GET['delete_id']))
  {

    $sql_query="SELECT * FROM registration where id='".$_GET['delete_id']."' ";
    $result=mysql_query($sql_query);
    while($row = mysql_fetch_assoc($result)) { 
      $region = $row['region'];
    }

    $sql_query="DELETE FROM registration WHERE id=".$_GET['delete_id'];
    mysql_query($sql_query);

    header("Location: report2.php?region=".$region);
    exit;
  }

?>
<script type="text/javascript">
    function delete_id(id) {
      if(confirm('Sure To Remove This Record ?')) {
          window.location.href='report2.php?delete_id='+id;
        }
    }
</script>