Need help adding delete button to every $row returned

Hello, currently my data gets printed to the screen by this code:

while($row = $result->fetch_assoc()) { ?>
  <tr>
    <td><?php echo $row['subcategory']; ?></td>
    <td><?php echo $row['costname']; ?></td>
    <!-- Added "€" sign infront of price !-->
    <td><?php echo "€ " . $row['price']; ?></td>
    <td><?php echo $row['info']; ?></td>
    <!-- Added Date Function to convert format !-->
    <td><?php echo date( "d/m/y",strtotime ($row['costdate'])); ?></td>
  </tr>

My plan is to also add a delete button for every row and then have it delete the query when pressed with an alert box for confirmation.

If anyone could give me a step in the right direction or an example i would be very gratefull!

One solution could be to add another <td></td> after the last one with a small form

<td>
   <form action = "process_form.php" method="post">
      <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
      <input type="submit" name="delete" value="Delete">
   </form>
</td>

or something to that effect. Then you can put your code to delete the record in the process_form.php.

1 Like

so i imagine that the name=“id” must contain the id of the query?
And the hidden input is actually $name = value when i refer to it?

I’m really sorry for these stupid questions but i’m just a beginner and i would really like to know :slight_smile:.

No. The name field id is just the name for the input. You could be somethin like random_id in there if you wanted to. But it’s recommend to name the field accordingly to what the data is given.

When you process the form, your $_POST array will contain two values: $_POST['delete'] will equal ‘Delete’ and $_POST['id'] will equal the id of the record that you wish to delete. Use that id in your mySQL query to delete the record.

Hey i made this script:

<?php
	session_start();

$id = $_POST['id'];
$sql = "DELETE FROM costs WHERE id='$id'";

?>

The problem i have now is that the data has not been deleted from the database… So something is wrong.

Well yes. You have made a query, but you haven’t told the script to execute that query. Do you have a database connection set up? What are you using for it - my_sqli or PDO?

1 Like

There is quite a bit more wrong here.
You need to first test if the form has been submitted.
Never put user input direct into a query like that, someone could very easily wipe out the whole table.
Sanitise, validate and use a prepared statement.

well i made this:

<?php
	session_start();

$id = $_POST['id'];

if($stmt = $conn->prepare("DELETE FROM costs WHERE id=?")) {
	$stmt->bind_param("i", $id);
	$stmt->execute();
}




?>

But this won’t work either it gives this error:

Fatal error: Call to a member function prepare() on null in \includes\deletecost.php on line 6

This.
And check first if the form is actually submitted.

if ($_SERVER["REQUEST_METHOD"] == "POST") {...}

yup, i forgot to include the db file my bad, It works now.

why do i really have to check if it is submitted? it only performs the script if they press delete :confused:

True if you add that test.
But without it, supposing someone lands on process_form.php, either inadvertently, through possibly history or back, or maybe one with malicious intent goes there, then what?
This will ensure it only fires when it’s supposed to.

1 Like

so this should be it then?

<?php

$conn = mysqli_connect("Connection private");

if (!$conn) {
  die("Connection failed:".msqli_connect_error());
}

	session_start();

$id = $_POST['id'];
if ($conn["REQUESTMETHOD"] == "POST") {
	if($stmt = $conn->prepare("DELETE FROM costs WHERE id=?")) {
		$stmt->bind_param("i", $id);
		$stmt->execute();
	}
}




?>

Sorry if i make these mistakes but i’m really starting to code since a few weeks…

That should be like I posted:-

if ($_SERVER["REQUEST_METHOD"] == "POST") { // Everything in here }

else { // What to do otherwise, possibly an error message or header redirect, up to you }

The connection and everything should only happen if this proves true.

You should also sanitise the ID to ensure nothing but an integer gets put in there.

    $id = preg_replace('#[^0-9]#i', '', $_POST['id']) ; // Get the clean ID

You may also want to check it’s not empty after that too.

Well i did what you said and it returns error so the connection fails:

<?php



if ($_SERVER["REQUESTMETHOD"] == "POST") {
	//connection to db
	$conn = mysqli_connect("connection private");
	//check the connection
	if (!$conn) {
	  die("Connection failed:".msqli_connect_error());
	}

	session_start();
	//set id to delete
	$id = $_POST['id'];
	//delete the row with the correct id
	if($stmt = $conn->prepare("DELETE FROM costs WHERE id=?")) {
		$stmt->bind_param("i", $id);
		$stmt->execute();
	}
} else {
	echo "Error";
}




?>
if ($_SERVER["REQUEST_METHOD"] == "POST") {}

Not:-

if ($_SERVER["REQUESTMETHOD"] == "POST") {}

Thank you very much it works now!

One more question:
Is there a way that if people click the delete button an alert box pops up and they have to accept?
I know this will be javascript probably, but is there nothing like that in php?

To just use php you would need a whole other “confirm” page. For a pop-up type thing, it could possibly be done via css, but it’s probably best a js thing.

1 Like

You are still mix matching procedural with OOP. You are using procedural for the database call and OOP for your prepared statements. Please be consistent since this will most likely confuse someone who is still new to PHP such as yourself.

OOP

$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);

$prepare = $mysqli->prepare('...');

Procedural

$mysqli = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);

$prepare = mysqli_prepare($mysqli, '...');
1 Like

Yeah you are right but if you are watching as many tutorials as i am and sites/forums you almost forget which thing is what.

Thanks for clearing that out space!

Thanks as always guys!