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.
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?
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.
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.
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";
}
?>
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.
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('...');