Delete confirm only using PHP - php

I want to delete links to delete images on an SQL database. I am tasked with creating a delete confirm option not using JavaScript just PHP.
require_once("photoalbum-common.php");
$pdo = connect();
if ( isset( $_GET['deletionid'])) {
$errorMessage = deletePhotograph( $pdo, $_GET['deletionid']);
if ( $errorMessage != "") {
print "<div class='errormessage'>$errorMessage</div>\n";
} else {
print "<div class='message'>Image deleted.</div>\n";
}
}
The code below is in "photoalbum-common.php".
<?php
function deletePhotograph( $pdo, $deletionid) {
$errorMessage = "";
// retrieve name of image file so we can delete it
$stmt = $pdo->prepare("SELECT `image` FROM `photographs` WHERE `photoid`=?");
$stmt->execute( array( $deletionid));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ( count( $rows) == 1) {
// delete file
unlink( "images/".$rows[0]['image']);
// delete database record
$stmt = $pdo->prepare("DELETE FROM `photographs` WHERE `photoid`=?");
$stmt->execute( array( $deletionid));
$affected_rows = $stmt->rowCount();
} else if (count( $rows) > 1) {
$errorMessage .= "ID matches more than one record. ";
} else {
$errorMessage .= "ID not found: nothing to delete. ";
}
return $errorMessage;
}
?>

Use something like this. An interstitial page, that accepts a GET request:
GET Request GET /delete.php?id=123
Are you sure you wanna delete?
POST Request POST /delete.php?id=123
Execute the PDO.
You are supposed to write the code for the PHP. If the answer is not enough for this, well, here we go:
<?php
if (count($_POST)) {
// POST Request
deletePhotograph();
} else {
// GET Request
?>
<p>Are you sure you wanna delete?</p>
<!-- Empty action will POST to the same page. -->
<form action="" method="POST"><input type="submit" value="I confirm, Delete" /></form>
<?php
}
?>

Related

Check if child data exists before deleting parent

I have news_Category and news table, here every news comes under one category,so before deleting new_category I want to display user a msg that child news exists in this category so u are not allowed to delete, If there are no child news than a confirm alert to user that "do u really want to delete".If he confirms the news category gets deleted.
HTML STUFF
<?php echo "<a style='color:red;''
href='delete.php?delete=$values[category_id]&
img=$values[category_image]'><i class='fas fa-trash-alt'></i></a>"; ?>
if ($_GET['msgError']) {
echo "<script>alert('First Delete The News Than Category');</script>";
}
if ($_GET['msg']) {
?>
<?php
}
?>
DELETE.PHP
if (isset($_GET['delete'])) {
$id= $_GET['delete'];
$img=$_GET['img'];
$obj=new commands();
$obj->delete_category($id,$img);
}
Delete Function
function delete_category($id,$img)
{
$stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
} else {
$sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
$sql->bindParam(':id', $id);
$sql->execute();
unlink("uploads/" . $img);
header('Location: news_category.php?msg="confirm"');
$this->con = null;
}
}
I am not able to make to logic here, how can I check whether the child news exists so i can display error msg and if there is no child news how to show confirm alert to allow delte
You need to check to see if the result is empty.
Something like this:
function delete_category($id,$img)
{
$stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($result)) {
header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
} else {
$sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
$sql->bindParam(':id', $id);
$sql->execute();
unlink("uploads/" . $img);
header('Location: news_category.php?msg="confirm"');
$this->con = null;
}
}
Edit due to extra details request
On the front end you just need to display the GET msgError like this:
<?php isset($_GET['msgError']) ? echo url_decode(base64_decode($_GET['msgError'])) : '' ?>
Where you want to show the message text.

How to remove a row from MySQL table data using html delete button in PHP

I am working on a project, for school. I currently have a product page to display an assortment of item includes image, description and price etc...
Under each product I have a delete button, when logged in as admin, which displays fine.
if (is_admin())
echo '<button>Delete item</button>'; }
I want to know how remove the row of data from MySQL table on clicking the delete button.
<?php
// Include need php scripts
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
include ("Includes/header.php");
if (!empty($_GET['cat'])) {
$category = $_GET['cat'];
$query = mysqli_query($db, "SELECT * FROM products WHERE category = '".$category."'");
} else {
$query = mysqli_query($db, "SELECT * FROM products");
}
if (!$query) {
die('Database query failed: ' . $query->error);
}
$deleted = mysql_query($db, "DELETE FROM products");
?>
<section>
<div id="productList">
<?php
$row_count = mysqli_num_rows($query);
if ($row_count == 0) {
echo '<p style="color:red">There are no images uploaded for this category</p>';
} elseif ($query) {
while($products = mysqli_fetch_array($query)){
$file = $products['image'];
$product_name = $products['product'$];
$image_id = $products['id'];
$price = $products['price'];
$desc = $products['description'];
echo '<div class="image_container">';
echo '<a href="viewProduct.php?id=' . $image_id . '"><p><img src="Images/products/'.$file.'" alt="'.$product_name.'" height="250" /></p>';
echo '' . $product_name ."</a><br>$" . $price . "<br>" . $desc;
echo '</div>';
if (is_admin()){
echo '<button>Delete item</button>';
}
}
} else {
die('There was a problem with the query: ' .$query->error);
}
mysqli_free_result($query);
?>
</div>
</section>
<?php include ("Includes/footer.php"); ?>
<!-- end snippet -->
You should post to a url with the id in the post data, then redirect back to where you were.
<?php
//html on productpage
if(isset($_GET['product_deleted'])){
if($_GET['product_deleted'] === 'true'){
echo 'The product was deleted';
}else{
echo 'The product could not be deleted';
}
}
if (is_admin()){
/**
* It's a good idea for the page that deletes to be different from the one your on, so that when you redirect back,
* they can refresh the page without getting something
* along the lines of 'refreshing with page will re-post the data'
*/
?>
<form method="POST" action="/product/delete.php">
<button>Delete item</button>
<input type="hidden" name="id" value="<?php echo $image_id; ?>" />
</form>
<?php
}
//PHP on /product/delete.php
if(is_admin() && $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['id'])){
//delete sql here
header('Location: /productpage.php?product_deleted=true'); //redirect back
}
One approach
Change the button to a a element and make the href look like this:
yourdomain.tld/products/delete/{id}
You have to echo the primary key from your mysql database at the id position. It will look like this:
yourdomain.tld/products/delete/5
Then you have to change your .htaccess in a way that all requests go to your index.php in your root project. At the index.php you can do the actually query then.
Update
Keep in mind that anyone visiting this URL can delete products with this approach. You have to make sure that only the admin can do that. The preferred method is a POST request.
You can also send the primary key parameter to your PHP script you are just showed. With this approach you don't need to edit your .htaccess. You may pass it as an URL parameter like this:
yourdomain.tld/your-script.php?delete-product={id}
In your script you can get the parameter like this:
<?php
if (isset($_GET['delete-product'])) {
// your mysql query to delete the product
} else {
// something else
}
If you want to delete the entire row of an record from your db you can do like this. So that you can pass the product id and delete the row. Just bind the id with query using bind parameters concept
$knownStmt=mysqli_prepare($conn, "DELETE FROM `YourTableName` WHERE `pdt_id` = ?;");
if( $knownStmt ) {
mysqli_stmt_bind_param($knownStmt,"d",$pdt_id);
mysqli_stmt_execute($knownStmt);
mysqli_stmt_close($knownStmt);
}

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");

Add and edit in one form php

I have two files .. addclient.php & Editclient.php.
I want to combine in one php form. can u please help me to do this
<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "add";
} else if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "edit"
}
?>
if $id already exist in the table than the row is updated otherwise it's an INSERT.
If you only have an $id : show the form with existing data in it.
If it's not a $id isn't populated : show an empty form.
<?php
if(isset($_GET['id'])) {
$id = intval($_GET['id']);
$stmt = $mysqli->prepare("SELECT id FROM table WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
if($stmt->num_rows > 0) {
// UPDATE
// Text field with the id
echo '<input type="text" name="id" value="'. $id. '"/>';
} else {
// INSERT
// Text field with no id
echo '<input type="text" name="id"/>';
}
}
?>
This validates the integer and makes sure it's one, queries the table for that specific id, if there is more than one row with that id then you need to update, else you need to insert.
<?php
if(isset($_GET['ID'])) {
$ID= $_GET['ID'];
// Use MySQL with $ID to check if the user is existing, and this string will either be 0 or 1
$existing = 0; // 0 = New 1 = Existing
//Add
if($existing== 0) {
}
//Edit
if($existing == 1) {
}
}
?>
Try this
<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "update";
}else{
$id = $_GET['id'];
echo "add"
}
?>
Can you try this,
<?php
if(isset($_GET['id'])) {
$id = $_GET['id'];
echo "Edit";
} else {
echo "Add"
}
?>
try this
if(isset($id) && !empty($id)){
echo "Update";
}else{
echo "Add";
}

MySQL database is updated with empty value when updating using PHP

I am new in php, i tried this coding i select a value in my drop down list i want a corresponding value to be updated, i have list of user name in my database and a ID for them, i am displaying the user name and when i want to update i written a sql query to find the member id and update to database but it's inserting a null value. Here is my code.
Dropdown list code
<?
session_start();
if(!isset($_SESSION[''])){
header("location:");
}
?>
<?php include('dbconnect.php'); ?>
<?php
$ed=$_GET['ed'];
$query=mysql_query("select * from table1 where id='$ed'");
$query2= "select * from table2";
$row=mysql_fetch_assoc($query);
if($_POST['Submit'])
{
$mem= $_POST['memid'];
$memname =mysql_query("select memid from table2 where name='$mem'");
$memname1= mysql_fetch_assoc($memname);
$tot_count = mysql_fetch_assoc($ro_count);
$date=date("d-m-Y");
$status="Active";
$onamo=mysql_real_escape_string($_POST['onamo']);
$heid = mysql_real_escape_string($_POST['memname1']);
if($_POST['heid']=='')
{
$namo1="*Required";
$ok=1;
}
if($_POST['onamo']=='')
{
$onamo1="*Required";
$ok=1;
}
$insert=mysql_query("update table1 set oname='$onamo', heid='$heid' where id='$ed'") or die('error');
if($insert)
{
header("Location");
}
}
?>
<body>
<div id="main_container"><br />
<div class="main_content">
<div class="center_content">
<div class="right_content">
<div class="form">
<form action="" method="post" name="fomo" enctype="multipart/form-data" onsubmit="return fall();" class="niceform">
<h1 align="center">Edit Referal Partner </h1>
<?
if($_GET['val']==1) { echo "<h1 class='FeatureBlockHeader' >Member Added Successfully</h1>"; } ?>
<fieldset>
<dl><dt><label for="Owner Name">Referal Partner Name</label></dt><dd><input name="onamo" type="text" size="53" id="onamo" value="<?=$row['oname']?>"/><b style="color:#CA0000"><?=$onamo1?></b></dd></dl>
<dl><dt><label for="">Health Executives</label>
<?php $result1 = mysql_query($query2);
echo'<select name="memid" >';
while($row = mysql_fetch_assoc( $result1 )) {
echo '<option value="'.$row['name'].'">' . $row['name'] . '</option>';
}
echo '</select>'; ?>
</b></dd></dt>
<dl><dt><label for="submit"></label></dt><dd> <input type="submit" name="Submit" value="Submit"></dd></dl></fieldset>
</table>
</form>
'
My database is updated with empty string, if i directly pass the dropdown value Name it's updating fine. But i want to update the corresponding memberid to my table. Please help me.
Stage 1:
You don't do anything if the field is blank. (Plus you have your logic wrong with $ok).
Suggested code would be:
$ok = 1; // assume ok unless we have an error
if($_POST['heid']=='')
{
$namo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if($_POST['onamo']=='')
{
$onamo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if ($ok)
{
// Do your update
$insert = mysql_query("update table1 set oname='$onamo', heid='$heid' where id='$ed'") or die('error');
if($insert)
{
header('location: ???');
exit(); // ALWAYS exit after a header redirect, otherwise the rest of the code will continue to work, then the redirect happens!
}
$ok = 0;
$error = 'Failed to update database'
}
// If you get here, you have an error condition.
** Stage 2:**
You should check for isset($_POST['onamo']) before getting the variable. Otherwise it would throw a warning. This will probably give you the error. You have a discrepancy between 'heid' and 'memname1'! :)
$ok = 1; // assume ok unless we have an error
if(!isset($_POST['heid']) || $_POST['heid']=='') // Or is it $_POST['memname1']?
{
$namo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if(!isset($_POST['onamo']) || $_POST['onamo']=='')
{
$onamo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if ($ok)
{
$onamo=mysql_real_escape_string($_POST['onamo']);
$heid = mysql_real_escape_string($_POST['memname1']); // Or is it $_POST['heid'] ??
// Do your update
$insert = mysql_query("update table1 set oname='$onamo', heid='$heid' where id='$ed'") or die('error');
if($insert)
{
header('location: ???');
exit(); // ALWAYS exit after a header redirect, otherwise the rest of the code will continue to work, then the redirect happens!
}
$ok = 0;
$error = 'Failed to update database'
}
// If you get here, you have an error condition.

Categories