Delete row when pressing button not working - php

So currently 160 servers are pulled from a database and stacked under each other:
<tr>
<td>
The last <td> in this row should trigger the removal of that specific row from the database but it doesn't and links me to the error page at this time.
Main code:
<?php
require_once "config/config.php";
$sql = "SELECT * FROM deployments";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['server'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['url'] . "</td>";
echo "<td>" . $row['port'] . "</td>";
echo "<td><span class='badge badge-warning'>ERROR</span></td>";
echo "<td><a href='config/delete.php?id=". $row['server'] ."' title='Delete Record' data-toggle='tooltip'><span class='fa fa-trash'></span></a></td>";
echo "</tr>";
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
Delete.php page code:
<?php
// Process delete operation after confirmation
if(isset($_POST["server"]) && !empty($_POST["server"])){
// Include config file
require_once "config/config.php";
// Prepare a delete statement
$sql = "DELETE FROM deployments WHERE server = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_server);
// Set parameters
$param_server = trim($_POST["server"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records deleted successfully. Redirect to landing page
header("location: ../deployments.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else{
// Check existence of id parameter
if(empty(trim($_GET["server"]))){
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
When the fa fa-trash icon is clicked the row that icon shares with the server name url port should be removed from the database.

You should use $_GET['id'] or $_REQUEST['id'] instead of $_POST["server"]
Replace your Delete.php code with below code
<?php
// Process delete operation after confirmation
if (isset($_GET["id"]) && !empty($_GET["id"])) {
// Include config file
require_once "config/config.php";
// Prepare a delete statement
$sql = "DELETE FROM deployments WHERE server = ?";
if ($stmt = mysqli_prepare($link, $sql)) {
// Set parameters
$param_server = trim($_GET["id"]);
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_server);
// Attempt to execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
// Records deleted successfully. Redirect to landing page
header("location: ../deployments.php");
exit();
} else {
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else {
// Check existence of id parameter
if (empty(trim($_GET["id"]))) {
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>

I've made some changes to the code myself, thanks for all the help, the removal is still not working and I keep getting the error message from the error.php page.
<?php
// Process delete operation after confirmation
if (isset($_GET["id"]) && !empty($_GET["id"])) {
$id = $_POST["id"];
// Include config file
require_once "config/config.php";
// Prepare a delete statement
$sql = "DELETE FROM deployments WHERE id = '$id'";
if ($stmt = mysqli_prepare($link, $sql)) {
// Set parameters
$param_id = trim($_GET["id"]);
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Attempt to execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
// Records deleted successfully. Redirect to landing page
header("location: ../deployments.php");
exit();
} else {
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else {
// Check existence of id parameter
if (empty(trim($_GET["id"]))) {
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="alert alert-danger fade in">
<input type="hidden" name="id" value="<?php echo trim($_GET["id"]); ?>"/>
<p>Are you sure you want to delete this record?</p><br>
<p>
<input type="submit" value="Yes" class="btn btn-danger">
No
</p>
</div>
</form>

Change your code to...
// Process delete operation after confirmation
if(isset($_POST["id"]) && !empty($_POST["id"])) {
$id = $_POST["id"];
//Include config file
require_once("config/config.php");
//Prepare a delete statement
$sql = "DELETE FROM deployments WHERE server = '$id' ";

Related

PHP - Form error alerts displays on page load

i am a newbee and just learning along the way. I have two forms on a page (I have only shown one of them as the other form is the same code with different variables). Both their error messages display on page load. How can I stop this?
I have read multiple posts regarding this but I still cannot find a solution.
<?php
if(isset($_POST['Update'])) {
$c_fname = $_POST['fname'];
$c_lname = $_POST['lname'];
$c_email = $_POST['email'];
$c_phone = $_POST['phone'];
// Save $_POST to $_SESSION
//query
$insert_det = "INSERT INTO Cus_acc_details(CUS_Fname,CUS_Lname,Cus_Email,CUS_Phone)
VALUES (?,?,?,?)
ON DUPLICATE KEY
UPDATE
Cus_acc_details.CUS_Fname = '$c_fname',
Cus_acc_details.Cus_Lname = '$c_lname',
Cus_acc_details.Cus_Email = '$c_email',
Cus_acc_details.CUS_Phone = '$c_phone'";
$stmt = mysqli_prepare($dbc, $insert_det);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sssi', $c_fname, $c_lname, $c_email, $c_phone);
/* execute query */
$r = mysqli_stmt_execute($stmt);
// if inserted echo the following messges
if ($r) {
echo "<script> alert('Saved')</script>";
}
} else {
echo "<b>Oops! we have an issu </b>";
}
?>
You have an else after your if (isset($_POST['Update'])). Inside that else you are displaying errors as if the user tried to submit the form. $_POST['Update'] will only be set if the user tried to submit the form. Move that else inside your if:
if (isset($_POST['Update'])) {
/* a bunch of code to insert into the DB */
// if inserted echo the following messges
if ($r) {
echo "<script> alert('Saved')</script>";
}else{
echo "<b>Oops! we have an issu </b>";
}
}
In Addition:
The commenter is right. You are at risk for SQL Injection. Please use prepared statements instead.
The problem is your else statement is running every time the variable $_POST['Update'] is not set.
One way to fix this is to move your error message inside your form checking code. Something like this would work:
if (isset($_POST['Update'])) {
/* unchanged code snipped */
if ($r) {
echo "<script> alert('Saved')</script>";
} else {
echo "<b>Oops! we have an issu </b>";
}
}
Hope that helps!

Updating SQL with form and PHP. Values resetting to 0 on submit?

I am attempting to create a simple form that updates a row in a MYSQL database based on what ID the row is.
I have managed to get the form and updating values working, but for one of my variables I need its new value to be added to it, based on the values of two other variables. (So like $currPoints = $currPoints+$addPoints-$remPoints;).
The problem I am facing is that whenever the form is submitted, $currPoints is either resetting to 0, then adding and subtracting the other values, or the value of $cuurPoints isn't being found so that it cannot add to it's original value.
I am not sure where specifically in my code I am going wrong so I will paste the whole page if that is okay!
My form function. This get's called on page load:
// creates the form
function renderForm($name = '', $currPoints = '', $addPoints = '', $remPoints = '', $reason = '', $error = '', $id = '')
{ ?>
<title>
<?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?>
</title>
<h1><?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form name="pointsForm" action="" method="post" style="margin-top:50px;">
<?php if ($id != '') { ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>Name: <?php echo $name; ?> / <?php echo $currPoints; ?></p>
<?php } ?>
<input type="number" name="addPoints" placeholder="Add Punk Points">
<input type="number" name="remPoints" placeholder="Remove Punk Points">
<input type="text" name="reason" placeholder="Reason">
<input type="submit" name="submit" value="Update Punk Points">
</form>
</body>
</html>
<script>
$(function() {
$('form[name="pointsForm"]').submit(function(e) {
var reason = $('form[name="pointsForm"] input[name="reason"]').val();
if ( reason == '') {
e.preventDefault();
window.alert("Enter a reason, fool!")
}
});
});
</script>
<?php
}
Then my PHP for editing a record:
Where I get the variables from the URL/form I have added $currPoints = $currPoints+$addPoints-$remPoints;
Then on my bind_param is just add $currPoints.
I believe I am going wrong somewhere around these lines... or where I SET currPoints = ? . should that be something else?
Forgive me I am just learning PHP.
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = $currPoints+$addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: index.php");
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: index.php");
}
}
}
?>
Sorry If I have been too vague. Please let me know if you need more information.
Thank you!
Oh found the error I think, you are never defining $currPoints before you try and use it, so you can't have $currPoints = $currPoints+.. because it isn't created yet. PHP more or less so will read line by line, so you have to query the SQL table and set $currPoints equal to the value from your database before you do $currPoints = $currPoints+$addPoints-$remPoints;
Ok, this probably won't work, but you should be able to figure out what I changed and adapt your code to work with it. I wouldn't say it's the 'proper' way, but it is a little easier to read and see what the code is doing when you have the if statements at the top to deal with what data is submitted vs not submitted.
if (!isset($_GET['id'] || !isset($_POST['submit'])))
{
echo "No Data!"
return;
}
if (!is_numeric($_POST['id']))
{
echo "Invalid ID!";
header("Location: index.php");
return;
}
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = 0;
//Check what the current points are first
// make sure the 'id' value is valid also
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
else
echo "Error: could not prepare SQL statement";
}
//Now update currPoints
$currPoints += $addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
else
echo "ERROR: could not prepare SQL statement.";
// redirect the user once the form is updated
header("Location: index.php");

How to delete the image path from a server using unlink in PHP?

I've almost finished my project but I'm stuck on a small problem I'm hoping to get help with. This is my first PHP/mysqli project and I'm still very "green". Any help is much appreciated.
I have been able to successfully upload and delete images from my database, however I can't seem to get the unlink command to delete the images from my server.
Please find below the code I am using in the background (hotel-imgdelete.php):
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
// confirm that the 'id' variable has been set
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get the 'id' variable from the URL
$id = $_GET['id'];
// delete image from server
$path = "../hotels/";
$image = "name";
unlink($path.$image);
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM hotels WHERE id = ? LIMIT 1"))
{
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: ../home.php");
}
else
// if the 'id' variable isn't set, redirect the user
{
header("Location: ../delete-hotel-images.php");
}
?>
This is the code I am using to view and select the images to delete
(delete-hotel-images.php)
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM hotels ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
$row->id;
echo "<div id='partner'><img src='hotels/" . $row->name . "'></a><br><br>";
echo "<center><a href='#' onclick='delete_user(". $row->id . ")'>Delete</a></center></div>";
}
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
I'm not entirely sure what your filesystem looks like, or what the file is supposed to be, but it looks like you're trying to delete "../hotels/name", since $image is set to the string "name".
I'm assuming this wasn't intentional so that could be the problem there. If, however, you are trying to delete a directory (since it appears to have no file extension) you will need to use "rmdir" and not "unlink".
How are the images laid out on your filesystem?
sorted
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get the 'id' variable from the URL
$id = $_GET['id'];
if ($stmt = $mysqli->prepare("SELECT id, name FROM hotels WHERE id=?"));
{
$stmt->bind_param("i", $id);
$stmt->execute();
}
$stmt->bind_result($id, $name);
$stmt->fetch();
$path = "../images/hotels/";
$image = $name;
unlink($path.$image);
$stmt->close();
include_once 'db_connect.php';
include_once 'functions.php';
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM hotels WHERE id = ? LIMIT 1"))
{
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: ../home.php");
}
else
// if the 'id' variable isn't set, redirect the user
{
header("Location: ../delete-hotel-images.php");
}

text versioning system using PHP MySQL

I am trying to create a system where a user can enter some text and another user can edit that input and another can edit the input that the second user has entered. This is the code that I have so far; it only works as a reply system to a post at the moment:
<?php
include 'includes/connection.php';
$query = "SELECT * FROM branches";
$result1 = mysql_query($query) or die(mysql_error());
while($person = mysql_fetch_array($result1)) { //As long as there is data, output the data
$id = $person['ID'];
$query2 = "SELECT * FROM branchesedit WHERE (parent_id = '$id' )";
$result2 = mysql_query($query2) or die(mysql_error());
echo "<h3>" . $person['Names'] . "</h3>";
echo "<p>" . $person['Lyrics'] . "</p>";
echo "Modify Song";
echo "<span> </span>";
echo "Delete Song";
while($row2 = mysql_fetch_array($result2)){
echo "<h3>" . $row2['Name'] . "</h3>";
echo "<p>" . $row2['LyricUpdate'] . "</p>";
}
}
?>
modify.php
<?php
if(isset($_POST['submit'])) {
$query = "SELECT ID FROM branches WHERE ID = $_GET[id]";
mysql_query("INSERT into branchesedit(`IDs`, `Name`, `LyricUpdate`, `parent_id`)
VALUES ('','$_POST[inputName]', '$_POST[ta]', '$_POST[id]')") or die(mysql_error());
echo "Song has been modified";
header("Location: index.php");
}
?>
Note:
You are using an isset() function on your modify.php where in your first given code (guessing your index.php) does not have a submit button. Only has a link that will redirect users to modify.php.
Better include a connection in your modify.php to establish connection so you can run your query.
You should consider using mysqli_* prepared statement rather than the deprecated mysql_* functions to prevent SQL injections.
Your modify.php in prepared statement:
<?php
/* INCLUDE HERE YOUR CONNECTION */
if(!empty($_GET['id'])) {
if($stmt = $con->prepare("SELECT IDs, Name, LyricUpdate FROM branchesedit WHERE parent_id = ? ORDER BY IDs DESC")){
$stmt->bind_param("i",$_GET["id"]);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id,$name,$lyricupdate);
$stmt->fetch();
?>
<h1>Modified by: <?php echo $name; ?></h1>
<form action="modify.php" method="POST">
<input type="hidden" name="id" value="<?php echo $_GET["id"]; ?>">
<input type="text" name="inputName" value="<?php echo $name; ?>"><br>
<textarea name="ta"><?php echo $lyricupdate; ?>"></textarea><br>
<input type="submit" name="submit">
</form>
<?php
$stmt->close();
} /* END OF PREPARED STATEMENT */
} /* END OF NOT EMPTY ID */
if(isset($_POST["submit"])){
if($stmt = $con->prepare("INSERT into branchesedit (`Name`, `LyricUpdate`, `parent_id`)
VALUES (?,?,?)")){
$stmt->bind_param("ssi",$_POST["inputName"],$_POST["ta"],$_POST["id"]);
$stmt->execute();
$stmt->close();
} /* END OF INSERT PREPARED STATEMENT */
echo "Song has been modified";
header("LOCATION: index.php");
} /* END OF ISSET SUBMIT */
?>
Summary:
When a user clicks on Modify Song link, user will be redirected to modify.php and then runs a query that will select the latest edit from your table branchesedit based from the ID being passed from the link.
User will see a form that is already filled up based from the last edit.
When submitted, it will still be in the modify.php and then runs an insert query.
After the insert query, it will redirect back to index.php
Replace the necessary connection variable I used in the prepared statement:
Example of your connection to be included in your queries (connection.php):
$con = new mysqli("Yourhost", "Yourusername", "Yourpassword", "Yourdatabase");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

Item doesn't get removed from database

I've been looking for hours atm but I can't seem to delete an item from my database. The $id is from $_GET['id']
<?php
$hostdb = "localhost";
$userdb = "root";
$pwdb = "";
$namedb = "cloud";
$dbCon = mysqli_connect($hostdb, $userdb, $pwdb, $namedb);
if(!$dbCon){
die("CONNECTION FAILED");
}
?>
Call to action remove button. Redirect to customers.php
<form action="customers.php" method="POST">
<button type="submit" name="remove" class="btn btn-sm btn-danger"><i class="glyphicon glyphicon-remove-circle"></i> Remove</button>
</form>
<?php
if(isset($_POST['remove'])) {
include("php/remove.php");
removeCustomer($id);
}
?>
Remove class
<?php
function removeCustomer($id){
include("connect.php");
$query = "DELETE FROM customers WHERE Id='$id'";
echo $id //gives me the right id
if(!mysqli_query($dbCon,$query) === TRUE){
echo "Error while removing customer from the database.";
}
mysqli_close($dbCon);
}
?>
UPDATE
When I redirect to the same page, then it does get removed.
But that's not the right way I suppose.
Ex. When I'm at page customer.php?id=2 and my form redirects to customer.php?id=2 then it's removed.
UPDATE 2 + SOLUTION
I've removed the "action" redirect in my form and it works fine.
There are a few things you can do to tighten up this code and make it more self-diagnostic when it goes wrong.
First, follow the convention on handling the result from mysqli_query(). Just check for the negation.
Secondly, make your error message announce the problem as well as the failure. Also, for troubleshooting's sake, make it announce success.
Thirdly, it's unlikely but possible that you don't have autocommit set. So commit your change immediately after you do the delete.
That will produce this code.
$query = "DELETE FROM customers WHERE Id='$id'";
if(!mysqli_query($dbCon,$query)){
echo "Error while removing customer ($id) from the database: "
. $dbCon->error;
}
else {
echo "Customer ($id) correctly removed from the database.";
}
if (!mysqli_commit($dbCon)) {
echo "Transaction commit failed: " . $dbCon->error;
}
mysqli_close($dbCon);
Finally, use a bind parameter to protect your code against cybercriminals. Then your code will look like this.
$query = "DELETE FROM customers WHERE Id=?";
$stmt = mysqli_prepare($dbCon, $query) || die ($dbCon->error);
mysqli_stmt_bind_param($stmt, 'd', $id) || die ($dbCon->error);
if(!mysqli_stmt_execute($stmt)){
echo "Error while removing customer ($id) from the database: "
. $dbCon->error;
}
mysqli_stmt_close($stmt);
if (!mysqli_commit($dbCon)) {
echo "Transaction commit failed: " . $dbCon->error;
}
mysqli_close($dbCon);
This business with the $stmt looks like a lot of extra work. But it's much safer -- proof against malicious rubbish in your $id variable.
Replace your If condition with this code.
if(mysqli_query($dbCon,$query) == FALSE){
echo "Error while removing customer from the database.";
}
OR
if(mysqli_query($dbCon,$query) != TRUE){
echo "Error while removing customer from the database.";
}
AND
if your Id is int then remove single quote in where condition.

Categories