sending phpmailer on data deletion - php

I have a form that adds a user to a mysql database table and emails the new information to a address (working).
Now I have a form that is used to delete records from the table but I am unable to get it to email the old users data before it deletes it.
for example if the user deletes the id 45 from the table, an email must be sent saying "A user was deleted from the table: 'Name','Phone','Extension'"
code for the delete.php:
<?php
require ("database.php");
?>
<?php
$this_Stud_ID =$_REQUEST['id'];
// sending query
mysql_query("DELETE FROM users WHERE id = '$this_Stud_ID'")
or die(mysql_error());
if($_POST['action'])
header("Location: index.php");
?>
<form action="<?php echo $_SERVER['php_self'] ?>" method="post">
Enter ID Number :<br><input type="text" name="id"><br />
<br><input type="submit" name="action" value="Delete!">
<br> <br>
<h3>
Main Menu
</h3>
</form>

You must fetch user data before delete.
Do something like this
<?php
require ("database.php");
if(isset($_POST['action'])){
if(isset($_REQUEST['id']) && (int)$_REQUEST['id']>0){
$this_Stud_ID =(int)$_REQUEST['id'];
$user_record=mysql_fetch_assoc(mysql_query('select * from users where id=' . $this_Stud_ID));
//now send an email to user or to anyone and use $user_record as user data
$to='';
$subject='';
$message='';
$headers='';
$mail_status=mail($to, $subject, $message, $headers);
if($mail_status){
mysql_query("DELETE FROM users WHERE id = '$this_Stud_ID'")or die(mysql_error());
header("Location: index.php");
exit();
}
}
}
?>
<form action="<?php echo $_SERVER['php_self'] ?>" method="post">
Enter ID Number :<br><input type="text" name="id"><br />
<br><input type="submit" name="action" value="Delete!">
<br> <br>
<h3> Main Menu </h3>
</form>

Look like the code isn't complete !
On form submit first fetch the data with WHERE id = $this_Stud_ID
and execute
mail("yourname#domain.com","Subject","phone no name ..etc");
then you can execute
mysql_query("DELETE FROM users WHERE id = '$this_Stud_ID'")
or die(mysql_error());
Please post your complete code !

Related

Can't delete record from MySQL database using PHP and HTML Form

I'm trying to create a form on a webpage, which takes an id number entered by the user, and deletes the corresponding record in a database. I'm unable to get it working.
This is the delete code which isn't working:
<?php
if (isset($_POST['deleteSubmit'])) {
$details = $conn->real_escape_string($_POST['deleteNum']);
$deleteSQL = "DELETE FROM userName WHERE id = '$details'";
$result = $conn->query($deleteSQL);
if (!$result) {
echo 'Error!';
exit($conn->error);
} else {
header('Location: index.php');
exit;
}
}
?>
<h4>DELETE NAME (DELETE)</h4>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="num">Enter User Reference to be Deleted:</label><br>
<input num="deleteNum"type="number"><br>
<input num="deleteSubmit" type="submit" value="Delete">
</form>
For reference, this is the post code which is working (it's being used to add names to the database):
<?php
if (isset($_POST['nameSubmit'])) {
$details = $conn->real_escape_string($_POST['newName']);
$insertSQL = "INSERT INTO userName (name) VALUES ('$details')";
$result = $conn->query($insertSQL);
if (!$result) {
echo 'Error!';
exit($conn->error);
} else {
header('Location: index.php');
exit;
}
}
?>
<h4>ENTER NAME (POST)</h4>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="fname">Enter Name:</label><br>
<input name="newName"type="text"><br>
<input name="nameSubmit" type="submit" value="Submit">
</form>
The database connection file is being called in both programs and is working for the post.php element, which is why I haven't included it or reference to it.
The database has one table called userName which contains two columns id (which is auto incremented) and name.
I've tried changing some of the syntax on the delete.php file with no success. I've ran the $deleteSQL code directly in my database and it works.
I see no error messages when enter an id and click the delete button.
For anyone who reads this in future, the query was solved by #kenlee;
(1) Change num="deleteSubmit" to name="deleteSubmit"
(2) change num="deleteNum" type="number" to name="deleteNum" type="number"
(3) Please use paratemerized prepared statement in your queries

Php form submit and page redirect

I am trying to redirect a to a new php page after the user has clicked on the submit button. I have got it to successfully send the form information to the MySQL database but then I cannot get a successful redirect.
I then changed some code and got it to successfully redirect but not send the form information to the database. My other php file is named nextForm.php and I have tried replacing the action="$_SERVER[PHP_SELF]" with the path to the nextForm.php file and I have tried using a require nextForm.php; line in the code where I want to redirect.
Here is the code I have currently:
<?php
//establish a connection to the MySQL db or terminate if ther is an error
$conn = mysqli_connect("localhost","root","mysql","covid_tech",3306) or die(mysqli_connect_error());
//HTML form to prompt user input
print <<<_HTML_
<FORM style="text-align:center" method="POST" action="$_SERVER[PHP_SELF]">
<div class="Customer_Name">
Enter Customer Name: <input type="text" name="Customer_Name" class="textbox">
</div>
<br/>
<div class="Contact_Name">
Enter Contact Name: <input type="text" name="Contact_Name" class="textbox">
</div>
<br/>
<div class="Contact_Phone">
Enter Contact Phone Number: <input type="text" name="Contact_Number" class="textbox">
<br/>
</div>
<button class="btn btn-1" style="text-align:center" onclick='disappear(this)' name="name_submit" method="POST" type="submit" value="find_cusName"><span>Enter Customer Name</span></button>
</FORM>
_HTML_;
//check to make sure the POST request was sent and check to make sure that there is a vlaue in the System POST variable
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['Customer_Name'])){
//SQL string to find the name that was input on the page
$find_name_sql = "SELECT cusName,cusID from customer where cusName = '$_POST[Customer_Name]'";
//run the query on the db
$result_find_name = mysqli_query($conn, $find_name_sql);
//Check to see if the query returned any rows
if(mysqli_num_rows($result_find_name) > 0){
//If it did, it should only be 1 row and we fetch it
$row = mysqli_fetch_row($result_find_name);
//set our current_id variable to the value in $row[1] which is the cusID attribute from the db
$current_id = $row[1];
}
else{
//sql statment to insert a new customer into the customer table of the db
$insert_first_customer = "INSERT INTO customer (cusName,contactName,contactNo) values('$_POST[Customer_Name]','$_POST[Contact_Name]','$_POST[Contact_Number]')";
//run the insert query
$add = mysqli_query($conn,$insert_first_customer);
}
//redirect to next form page here
}
mysqli_close($conn);
?>
The action attribute simply works as a way to direct your GET/POST requests. If you would like to redirect after running your PHP code, you should use the header() function or use a meta tag.
Example:
header('Location:'.$_SERVER['SERVER_NAME'].'/nextForm.php');
or
echo '<meta http-equiv="refresh" content="0;url=nextForm.php">';
and finish your code with the exit() function so an attacker could not bypass your redirect.

mysql table not deleting values

I have a mysql data table that holds user information such as name,department,extension and phone number
Now I have a delete query that deletes a user based on the extension number the admin enters.
It was working yesterday and I have not changed a thing so I have no idea what could be wrong.
According to my code it must delete the user and then display the table. Now it does all that but the user still exists.
<?php
error_reporting(0);
require ("database.php");
session_start();
if (!isset($_SESSION['CheckLogin'])) { header("Location: login.php"); }
if($_POST['action'])
{
$this_user_ext =$_GET['extension'];
// sending query
mysql_query("DELETE FROM users WHERE extension = '$this_user_ext'")
or die(mysql_error());
include('maildelete.php');
$extension=$_POST['extension'];
header("Location: index.php");
}
?>
<center>
<form action="" method="post">
Enter 4 Digit Extension Number :
<br>
<input type="text" name="extension">
<br>
<h2>
<input type="submit" name="action" value="Delete Extension">
<br>
</h2>
<h3>
Main Menu
</h3>
</form>
</center>
You have used POST method but you are using $_GET so
change $this_user_ext =$_GET['extension']; to $this_user_ext =$_POST['extension'];
Inside your form's tag having a method POST. You're sending the POST request, not the GET request. Use this code instead $this_user_ext = $_POST['extension'];
<?php
error_reporting(0);
require ("database.php");
session_start();
if (!isset($_SESSION['CheckLogin'])) { header("Location: login.php"); }
if($_POST['action'])
{
$this_user_ext =$_POST['extension'];
// sending query
mysql_query("DELETE FROM users WHERE extension = '".$this_user_ext."'")
or die(mysql_error());
include('maildelete.php');
$extension=$_POST['extension'];
header("Location: index.php");
}
?>
<center><form action="" method="post">
Enter 4 Digit Extension Number :<br><input type="text" name="extension">
<br><h2><input type="submit" name="action" value="Delete Extension">
<br></h2>
<h3>
Main Menu
</h3>
</form>
</center>
I hope U got it :) Enjoy..

Message that database is updated after redirecting

I'm new to PHP. I want to display a message that the database is updated after each time I redirect it after entering the data.
$sql = "INSERT INTO incoming (recipt, userid, username, money)
VALUES ('$recipt', '$userid', '$username', '$money')";
if ($conn->query($sql) === TRUE) {
echo "<script>window.open('incoming2.php','_self')</script>";
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
2 methods
1-you can redirect to any page adding message in get variable and check at that page if that variable is set then display it as message
//redirect to index.php with msg as
header('location:index.php?msg=2 records updated');
//at index page where you want to display message
if(isset($_GET['msg']) && !empty($_GET['msg'])){
echo '<p class="myMsg">'.$_GET['msg'].'</p>'
}
2- second method is to save the message to session variable and access it at page but you will have to unset that variable as below
//sending message assuming session_start() is written at to of all pages
$_SESSION['msg']="2 records updated or what ever your message is";
//where you want to display message
if(isset($_SESSION['msg']) && !empty($_SESSION['msg'])){
echo '<p class="myMsg">'.$_SESSION['msg'].'</p>'
unset($_SESSION['msg']);
}
Pass the message to your url:
echo "<script>window.open('incoming2.php?message=New+record+created+successfully','_self')</script>";
Then you can get the message in incoming2.php:
echo urldecode($_GET['message']);
Be careful: sanatize your input!
Use header("Location: incoming2.php"); instead of echoing JS.
Also, check your SQL statement for SQL injection vulnerabilities.
If you are posting the data on the same page you could do the following:
<?php
if(isset($_REQUEST["submit"])){
// mySQL code here
// return either success or failed
$confirmation="success";
}
?>
<html>
<head>
<title>Feedback</title>
</head>
<body>
<div>
<?php
if(isset($confirmation)){
echo $confirmation;
}
?>
</div>
<form method="post" action="">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" Value="Submit">
</form>
</body>
</html>
If you are sending the data to a separate page:
On the receiving page:
<?php
// mySQL code here
// return either success or failed
//redirect to index.php with confirmation as true or false
header('location:index.php?confirmation=success');
?>
and on the page that you Sent the data from:
<html>
<head>
<title>Feedback</title>
</head>
<body>
<div>
<?php
//at index page where you want to display message
if(isset($_GET['confirmation']) && !empty($_GET['confirmation'])){
echo $_GET['confirmation'];
}
?>
</div>
<form method="post" action="uploaddata.php">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" Value="Submit">
</form>
</body>
</html>
You can then use CSS3 animations to fade the message in and out for a better user experience :-)

Submit action message is showing when refresh the page

When I refresh/reload the page the message(Host Name, User Name and Database Name are mandatory.) is showing. I prefer to show the message only after the submission of form.
Consider my index.php page:
// Create database
$sql = "CREATE DATABASE $dbname";
if (mysqli_query($conn, $sql)) {
echo "<div class='msg'>Database created successfully</div>";
} else {
echo "<div class='msg'>Error creating database: " . mysqli_error($conn) ."</div>";
}
mysqli_close($conn);
}else{
echo "<div class='msg'>Host Name, User Name and Database Name are mandatory.</div>";
}
}?>
<form method="post" action="index.php" class="dbform" >
<table>
<tr><td>Host Name</td><td><input type="text" name="hostname" value="localhost"></td></tr>
<tr><td>User Name</td><td><input type="text" name="username"></td></tr>
<tr><td>Password</td><td><input type="text" name="pass"></td></tr>
<tr><td>Database Name</td><td><input type="text" name="dbname"></td></tr>
<tr><td colspan="2" align="center"><input type="submit" name="subbtn" value="Create"></td></tr>
</table>
</form>
Expected bahaviour: When click the submit button, if the fields are empty show the Host Name, User Name and Database Name are mandatory. message, It is working ok.
But when I refresh the page the message is also showing. How can I solve this?
It's because the browser is reloading the last request you performed on that page, which is a POST request to the index.php.
When you hit reload it is again performing that same request.
Most browsers ask for a confirmation before resubmitting a post request.
What you can do solve you problem is store your messages in session and redirect to the page.
Start of your PHP code add
session_start();
Then store your messages in session
$_SESSION['msg'] = 'Your message';
Then when you have processed the current request redirect.
header('Location: YOUR_URL');
die();
Then you can check if there is any message and output
<?php if (!empty($_SESSION['msg']) : ?>
<div class='msg'><?php echo $_SESSION['msg']; ?></div>
<?php endif; ?>

Categories