0

I have a somefile.php and someotherfile.js with the code as below

javascript file
function deleteSelectedRow() {
  return (confirm('Are you sure you want to delete this record)) 
      };
<!DOCTYPE html>

<html lang=" en">

<head>
  <title> Title </title>
</head>

<body>
  <h1>Select the user to delete from the list below </h1>

  <form action="" method="POST">
    <?php
            if(require_once('../SQL/mySQL_connect.php'))
            {                
                $query = "SELECT id, FirstName, LastName, PhoneNumber FROM participants ORDER BY id ASC";
                $userDetails = @mysqli_query($mysqli, $query);
            }
            else
            {
                echo "Couldn't connect to database";
                echo mysqli_error($mysqli);
            }    
           // mysqli_close($mysqli);
            
        ?>
      <br><br><br>


      <table name="userDetailsTable" id="userDetailsTable" align="left" cellspacing="7" cellpadding="8">
        <tr>
          <td align="center"><b>S No</b></td>
          <td align="center"><b>Id</b></td>
          <td align="center"><b>Rank</b></td>
          <td align="center"><b>First Name</b></td>
          <td align="center"><b>Last Name</b></td>
        </tr>
        <?php
                for($i = 1; $i <= mysqli_num_rows($userDetails); $i++)
                // while($row=mysqli_fetch_array($userDetails))
                {
                    $row=mysqli_fetch_array($userDetails);
                    echo '<tr>
                    <td align ="center" >'. $i .'</td>
                    <td align ="center" >' . $row['id'] . '</td>
                    <td align ="center">' . $row['Rank'] . '</td>
                    <td align ="center">' . $row['FirstName'] . '</td>
                    <td align ="center">' . $row['LastName'] . '</td>    
                    <td align ="center"> <input type = submit name="delete" value="delete" onclick="return deleteSelectedRow();" ></input></td>';
                    echo '</tr>';
                }
            ?>
      </table>
  </form>

  <?php
       
        if(isset($_POST['delete']))
        {
            require_once('../SQL/mySQL_connect.php');
            $query="DELETE FROM `participants` WHERE `participants`.`id` = ".$_POST['IDNumber']."";
            $response = @mysqli_query($mysqli, $query);
            if($response)
            {
                echo "Deleted from Database Successfully";
            }
            else
            {
                echo "Couldn't Delete from database";
                echo'<br>';
                echo mysqli_error($mysqli);
            }
            mysqli_close($mysqli);
        }
    ?>

</body>

What this code does is as follows

  1. Connects to database and retrieves the user details
  2. Creates a table and prints out the user details in it
  3. user clicks on delete button in front of any record and it gets deleted after confirmation
  4. A success message is displayed that the message is deleted

What I want to do is that after displaying the success message the above printed table should get updated automatically so that user is confirmed that the id no longer exists in the table

I tried the following solutions

  1. reload page just before the success message is displayed so that user sees the success message as well as the updated table as well (since reload will re-connect to database and refetch the table)

    I tried to use "location.reload(true)" command but i can't figure out where to place this line so that it gets executed just before the success message is displayed.

Any help is much appreciated

Community
  • 1
  • 1
MSM
  • 410
  • 6
  • 16
  • You can try `header("Location: " . "http://" . $_SERVER['HTTP_HOST'] . $location);` after `if($response)` – absin Oct 16 '18 at 15:25
  • You're removing entry after print the table. Move the removal block before the *SELECT* query. This should work with page reload with *location.reload();*. – Ernani Azevedo Oct 16 '18 at 15:26
  • 1
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php). [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Oct 16 '18 at 15:29
  • 1
    CUT and PASTE your if(isset($_POST['delete'])) { } code between

    and

    tag
    – Mangesh Sathe Oct 16 '18 at 16:00

2 Answers2

2

A few things:

  1. you'll want the delete operation to be the first thing you do on the page (if it's a form submit) because otherwise you'll print the "pre-deleted" table.

  2. you need to pass the ID through post in the form. It's easier if you just have a unique for for every row, and have a hidden ID input for each.

  3. The confirm is better attached to the form submit event, because otherwise you'll miss other, non-click, input methods.

  4. Your delete operation, as it was written in the question, is susceptible to an SQL Injection attack. You'll want to escape that POST value.

Something like the below should work

function deleteSelectedRow() {
  return (confirm('Are you sure you want to delete this record)) 
      };
<?php
 $message = '';
 $connected = false;
 if(require_once('../SQL/mySQL_connect.php'))
 {
    $connected = true;
 }
        if($connected && isset($_POST['delete']))
        {
            $id_to_delete = mysqli_real_escape_string($mysqli, $_POST['IDNumber']);//escape value to prevent sql injection attack
            $query="DELETE FROM `participants` WHERE `participants`.`id` = ".$id_to_delete."";
            $response = @mysqli_query($mysqli, $query);
            if($response)
            {
                $message = "Deleted from Database Successfully";
            }
            else
            {
                $message = "Couldn't Delete from database";
                $message .='<br>';
                $message .= mysqli_error($mysqli);
            }
            //mysqli_close($mysqli);
        }else{
          $message = "unable to connect to database";
        }
    ?><!DOCTYPE html>

<html lang=" en">

<head>
  <title> Title </title>
</head>

<body>
  <h1>Select the user to delete from the list below </h1>

  
    <?php
            if($connected)
            {                
                $query = "SELECT id, FirstName, LastName, PhoneNumber FROM participants ORDER BY id ASC";
                $userDetails = @mysqli_query($mysqli, $query);
            }
            else
            {
                echo "Couldn't connect to database";
                echo mysqli_error($mysqli);
            }    
           
            
        ?>
      <br><br><br>
      
<?php if($message){ /* do we have a success/error message from the delete operation? */ ?>
  <p><?php echo $message; ?></p>
<?php } ?>

      <table name="userDetailsTable" id="userDetailsTable" align="left" cellspacing="7" cellpadding="8">
        <tr>
          <td align="center"><b>S No</b></td>
          <td align="center"><b>Id</b></td>
          <td align="center"><b>Rank</b></td>
          <td align="center"><b>First Name</b></td>
          <td align="center"><b>Last Name</b></td>
        </tr>
        <?php
                for($i = 1; $i <= mysqli_num_rows($userDetails); $i++)
                // while($row=mysqli_fetch_array($userDetails))
                {
                    $row=mysqli_fetch_array($userDetails);
                    echo '<tr>
                    <td align ="center" >'. $i .'</td>
                    <td align ="center" >' . $row['id'] . '</td>
                    <td align ="center">' . $row['Rank'] . '</td>
                    <td align ="center">' . $row['FirstName'] . '</td>
                    <td align ="center">' . $row['LastName'] . '</td>    
                    <td align ="center"> <form action="" method="POST" onsubmit="return deleteSelectedRow();"><input type="hidden" name="IDNumber" value="'.$row['id'].'" /><input type = submit name="delete" value="delete"></form></td>';
                    echo '</tr>';
                }
            ?>
      </table>

<?php if($connected){
  mysqli_close($mysqli);
} ?>


</body>
Community
  • 1
  • 1
dgeare
  • 2,618
  • 5
  • 18
  • 28
  • I tried with the edits as you mentioned. But when I delete any record the page reloads and says "mysqli_query(): Couldn't fetch mysqli in..." for every query I have called in whole file. Probably somewhere connection to server is broken or is it something else? – MSM Oct 16 '18 at 17:03
  • the whole error statement is "Warning: mysqli_query(): Couldn't fetch mysqli in C:\xampp\htdocs..." for all the queries called in the file – MSM Oct 16 '18 at 17:41
  • 1
    @MShajeehMustafa I didn't pay close enough attention to your db connection. I've adjusted the example to account for the use of `require_once`. I imagine the errors were related to the connection being closed, but not reopened (because you already required the file once earlier on the page.) It's not a great solution, but without seeing and making changes to `mySQL_connect.php` it's the best I could do. – dgeare Oct 16 '18 at 17:48
  • probably I'll have to start some session in mySQL_connect.php or something similar. Nevertheless, thanks so much – MSM Oct 16 '18 at 17:55
  • +1 but I would mention that instead of escaping the input, it would be better to adopt the better practice of parameterized queries. – GrumpyCrouton Oct 16 '18 at 20:34
1

You need to store the Success/Error message in a $_SESSION["flash"] instead of show by echo and after delete the user you must redirect to the same page. On the top of the page, if isset the $_SESSION["flash"] you can show the message and remove it from the session. In code:

if(isset($_POST['delete']))
    {
        require_once('../SQL/mySQL_connect.php');
        $query="DELETE FROM `participants` WHERE `participants`.`id` = ".$_POST['IDNumber']."";
        $response = @mysqli_query($mysqli, $query);
        if($response)
        {
            $_SESSION["flash"] = "Deleted from Database Successfully";
        }
        else
        {
            $_SESSION["flash"] = "Couldn't Delete from database";
            //echo'<br>';
            //echo mysqli_error($mysqli);
        }
        mysqli_close($mysqli);
        header('Location: '.$_SERVER['PHP_SELF']); 
    }

and on the top of the page of before isset($_POST['delete']):

if(isset($_SESSION["flash"])){
   echo $_SESSION["flash"];
   unset($_SESSION["flash"]);
}

don't forget to start_session() on the top of the page. I'll notice that your code have a SQL Injection Vulnerability. You shouldn't do MySQL queries without validate GET and POST input data.

blimes
  • 69
  • 9
  • You should mention in your answer that the code is vulnerable to SQL Injection. – GrumpyCrouton Oct 16 '18 at 15:55
  • Yes, in a comment, which can be removed at any time for any reason. It's better to cover your own bases, that comment may not exist forever, and when it is deleted and people view this answer in the future they may not realize it is vulnerable (Which is the problem with tons of tutorials, they are vulnerable but new people don't know that) – GrumpyCrouton Oct 16 '18 at 15:57
  • Ok sorry I'm doing it immediatly – blimes Oct 16 '18 at 15:58