1

I tried to add a delete "button"(link to file with function) it should delete a row from the database, but it didn't work. I looked for tutorials and answers on forums but found nothing how solve for my problem.

<td><a href="includes/delete.inc.php?commentId=<?php echo $row["commentId"]; ?>">Delete</a></td>

link from code:

link from code

The link works correctly, but when I tried to delete it just doesn't want to take 'commentId' variable and go back to test.php page

Table on website:

table on website

dbh.inc.php

<?php

$serverName = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "php-login";


$conn = mysqli_connect($serverName, $dBUsername, $dBPassword, $dBName);


if (!$conn){
    die("connection failed: " . mysqli_connect_error());
}

test.php

<?php
include_once 'header.php';
include "includes/dbh.inc.php";
include 'includes/test.inc.php';
?>


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="box">
            <h4 class="display-4 text-center">Comments</h4><br>
            <?php if (isset($_GET['success'])) { ?>
            <div class="alert alert-success" role="alert">
              <?php echo $_GET['success']; ?>
            </div>
            <?php } ?>
            <table class="table table-striped">
              <thead>
                <tr>
                  <th scope="col">#</th>
                  
                  <th scope="col">Username</th>
                  <th scope="col">Comment</th>
                  <th scope="col">Action</th>
                </tr>
              </thead>
              <?php
                $i=0;
                while($row = mysqli_fetch_array($result)) {
                ?>
                
                <td><?php echo $row["commentId"]; ?></td>
                <td><?php echo $row["usersUid"]; ?></td>
                <td><?php echo $row["comment"]; ?></td>
                <td><a href="includes/delete.inc.php?commentId=<?php echo $row["commentId"]; ?>">Delete</a></td>
                </tr>
                <?php
                $i++;
                }
                ?>
            </table>      
        </div>
    </div>
</body>
</html>

test.inc.php

<?php  

include "dbh.inc.php";

$sql = "SELECT * FROM commenttb ORDER BY commentId DESC";
$result = mysqli_query($conn, $sql);

delete.inc.php

<?php

include "dbh.inc.php";
if(isset($_GET['commentId'])) {
   $id = $_GET['commentId'];
   $delete = "DELETE FROM `commenttb` WHERE `commentId` ='$id'";
   $result = mysqli_query($conn, $delete);
   if ($result) {
      header("Location: ../test.php?success=successfully deleted");
   } else {
      header("Location: ../test.php?error=unknown error occurred");
   }
}else {
   header("Location: ../test.php?error=smth gone wrong");
}

If I press on the link "delete" it should take 'commentId' variable from row e.g. 5 and by SQL query from delete.inc.php file delete row with this id from my database

I tried change $_Get to $_POST and add method="POST" to link on delete.inc.php file, but it didn't work

MaxDex
  • 11
  • 2
  • 2
    `add method="POST" to link`...that only applies to forms, not links. Always read the manual – ADyson Jan 03 '23 at 16:49
  • **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Jan 03 '23 at 16:49
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use it again. – ADyson Jan 03 '23 at 16:49
  • Never configure your web app to login to the database as `root`. Root can do whatever it likes, so on top of the SQL injection vulnerabilities this just leaves your database an open book for hackers. Instead create a separate user account specifically for this application which has only the permissions it actually _needs_ in order to work properly. Don't even use the root account as a shortcut during development or testing, because you need to test your account permissions as well - otherwise when you go live you might have unexpected errors relating to the user account setup. – ADyson Jan 03 '23 at 16:50
  • Please bring your error handling into the 21st century. Add `mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` before your `mysqli_connect()` (or `new mysqli()`) command, and this will ensure that errors with your SQL queries are reported correctly to PHP automatically. That way you don't need to clutter your script with repetitive code to keep checking errors after every mysqli command. Also you're losing info by just outputting "unknown error" when queries fail...it's not unknown, if you actually check for it! Your overall code is very archaic, unfortunately. – ADyson Jan 03 '23 at 16:50
  • What does `just doesn't want to` mean in reality? What does the code actually do, if it doesn't do what you expected? Do you get an error, or unexpected output? Or redirected somewhere else? Or what? be specific and clear about the problem, please. Knowing what the code _does_ do is at least as valuable (if not more so) than knowing what it _doesn't_ do. Remember, we can't run this for ourselves, so you need to tell us what's happening. – ADyson Jan 03 '23 at 16:59
  • If I press on the link "delete" it should take 'commentId' variable from row e.g. '5'(as photo from begining) and by SQL query from delete.inc.php file delete the row with this id from my database – MaxDex Jan 03 '23 at 17:07
  • Yes I already understand that. What I asked you was what the code currently does _instead of_ that. We need to understand where the mistake is happening. Observing the current behaviour in detail usually provides clues to that (as well as adding the better error handling I mentioned above). – ADyson Jan 03 '23 at 17:10
  • instead of `isset($_GET['commentId'])) {...` code just do `else { header("Location: ../test.php?error=smth gone wrong"); }` – MaxDex Jan 03 '23 at 17:11
  • That's pretty strange, given what you've shown us about the URL. Please put `var_dump($_GET);` before the `isset($_GET['commentId'])) ` line, and paste the output of that into here. – ADyson Jan 03 '23 at 17:13
  • I put var_dump($_GET); like that: `var_dump($_GET); if(isset($_POST['commentId'])) {...` but nothing chenged, maybe I did wrong? – MaxDex Jan 03 '23 at 17:18
  • Ok so 1) var_dump always outputs _something_. But you're redirecting away from the page which might obscure it, so please just comment out all the `header` commands in your delete.inc.php file for now, so we can debug that file. And 2) Why are you suddenly changing to `if(isset($_POST['commentId']))`?? Your hyperlink will always sent a GET request, with the data in the querystring, so the commentId will never be in $_POST. I don't know why you did that, it makes no sense. Also, please don't randomly change other stuff while we're in the middle of helping you, it gets confusing for us. – ADyson Jan 03 '23 at 17:21
  • ` string(1) "5" } – MaxDex Jan 03 '23 at 17:23
  • Again, stop randomly changing things I didn't tell you to. It's not helpful. Change one thing at a time, in a controlled way. – ADyson Jan 03 '23 at 17:30
  • But there should be no reason why this code doesn't go into the `if` block now. So please put something like `if(isset($_GET['commentId'])) { echo "here";` and see if it echoes "here". – ADyson Jan 03 '23 at 17:31
  • I only changed $_POST to $_GET on your advice, sorry if it is disturbing you – MaxDex Jan 03 '23 at 17:32
  • oh, I am an idiot or smth, i changed $_POST to $_GET and it suddenly start working, thank you so much! – MaxDex Jan 03 '23 at 17:35
  • `I only changed $_POST to $_GET on your advice`...no, it was $_GET in the code you posted originally - look at your question! Then you randomly changed it in the comments. And then you (even more randomly) moved code outside the `if` statement. I didn't ask you to do any of that. – ADyson Jan 03 '23 at 17:40
  • `it suddenly start working`...see the very first comment I made on this thread, about something you wrote in the question originally, I already told you POST would never work. ` – ADyson Jan 03 '23 at 17:42
  • ok I see, I tried to fix it by my self and did only worse, and, when I delete all not necessary parts that you said it starts working, anyway thank you for your help! – MaxDex Jan 03 '23 at 17:48

0 Answers0