I have database generated content in a table with edit and delete buttons in a form at the end of the row.
<td>
<form action="?" method="post">
<div class="">
<input type="hidden" name="id" value="<?php htmlspecialchars($item['id']); ?>">
<input type="hidden" name="action" value="edit_daily_shift_report">
<input type="submit" value="Edit" onclick="return confirm('Edit this report?');">
<input type="hidden" name="action" value="delete_daily_shift_report">
<input type="submit" value="Delete" onclick="return confirm('Delete this report?');">
</div>
</form>
</td>
If I remove the delete button, the edit code works fine. But with both buttons present, the edit button fails and the item in the row is deleted. I am stumped. Not only is the action value of the edit button ignored, the action value of the delete button is executed. Any help is appreciated!
Here is the controller edit and delete code:
/*********************** Edit Daily Shift Report ************************/
if (isset($_POST['action']) && $_POST['action'] === 'edit_daily_shift_report')
{
include '../includes/dbconnect-local.php';
try
{
$sql = 'SELECT * FROM daily_shift_report WHERE id = :id';
$s = $db->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error deleting data.' . $e->getMessage();
include 'error.html.php';
exit();
}
// Assign page title value
$pageTitle = 'Edit Daily Shift Report';
// Store single row resut in $item associative array
$item = $s->fetch(PDO::FETCH_ASSOC);
// Display report content in form
include 'edit_daily_shift_report.html.php';
exit();
}
/********************* Delete from Daily Shift Report *******************/
if (isset($_POST['action']) && $_POST['action'] === 'delete_daily_shift_report')
{
include '../includes/dbconnect-local.php';
try
{
$sql = 'DELETE FROM daily_shift_report WHERE id = :id';
$s = $db->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error deleting data.' . $e->getMessage();
include 'error.html.php';
exit();
}
echo '<span style="color:#ff0000;">Daily Shift Report DELETED successfully!</span>';
}
Thank you.
You need to understand how the post request works. As you know, you have two action fields, one for delete and one for edit.
Your problem is in short that there is no way to Connecticut specific input fields to different buttons.
What i would rather suggest is that you set the name of the buttons to action and the value as the value you already use for the hidden fields.
With this you also have to make a minor change in your html. Instead of:
<input type="submit" value="something" onclick="something">
Use this:
<button name="action" value="edit" onclick="something">Edit</button>
And the same goes for delete button
When you use button tag instead of input, you can set a value to the button which is different from the display, which makes it a cleaner PHP code when checking the value of $_POST['action'] afterwards
Related
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
I am trying to present the user with a confirm yes/no prompt before deleting an author from a Mysql Database. When a user hits Delete in the authors.html.php, the controller includes a confirm.php. The confirm.php prompts the user for a yes or no to confirm. If the yes button is clicked, the confirm.php is meant to pass the id back to the controller which then checks if the action isset, and if yes, delete the author based on the id.
Unfortunately the author does not get deleted, so the issue is with the the inclusion of the confirm prompt. Without the confirm include, the script works perfectly well, but I want to figure out what is going wrong and it's all too easy to use Javascript.
Any help appreciated.
My controller: index.php
//inlcude the data connection.
include $_SERVER['DOCUMENT_ROOT'] . '/authors/includes/db.inc.php';
try
{
$result = $pdo->query('SELECT id, name FROM author'); //Rows of a result set returned by fetch are represented as associative arrays,
}
catch (PDOException $e)
{
$error = 'Error fetching authors from the database!';
include 'error.html.php';
exit();
}
foreach ($result as $row)
{
$authors[] = array('id' => $row['id'], 'name' => $row['name']);
}
include 'authors.html.php';
if(isset($_POST['action']) and $_POST['action'] == 'Delete') {
include "confirm.php";
if(isset($_POST['action']) and $_POST['action'] == 'Yes') {
try {
$sql = 'DELETE FROM author WHERE id = :id';
$s = $pdo -> prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch (PDOException $e) {
$error = "Error deleting author.";
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}// if yes
} // end if isset delete
The authors.html.php then displays a list of authors:
<?php foreach ($authors as $author): ?><!-- loop through the list of authors pulled from the database by the controller -->
<li>
<form action="" method="post">
<div>
<?php htmlout($author['name']); ?> <!--display a list of authors and an edit and delete button-->
<input type="hidden" name="id" value="<?php
echo $author['id']; ?>">
<input type="submit" name="action" value="Edit">
<input type="submit" name="action" value="Delete">
</div>
</form>
</li>
<?php endforeach; ?>
confirm.php ......
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $author['id']; ?>">
<input type="submit" name="action" value="Yes">
<!--input type="submit" name="action" value="No"-->
</form>
Strictly speaking in terms of PHP, Instead of trying to process everything in a single action file (controller in MVC), what you should be doing is.. Make the second form to post to a different controller.
Say you have a form/table that contains the button/form that deletes the author. Let that form/button call a file named as confirm.php with the id of that author passed.
Inside the confirm page you render the confirm form with the yes/no input. And then this confirm.php will post to a delete.php which will check if the confirmation value is set inside the $_GET/$_POST and proceed as such.
Also on a side note I recommend that you learn some very basic javascript and use the confirm() function.
Also on a side side note, I strongly recommend that you learn some validation, sanitization, escaping, and about sessions.
Sorry I cant put comment in your Post, just a answer (I dont have required reputation).
So, your logic is wrong, see:
if(isset($_POST['action']) and $_POST['action'] == 'Delete') {
include "confirm.php";
if(isset($_POST['action']) and $_POST['action'] == 'Yes') {
When the $_POST['action'] == 'Yes' the script will not pass to the:
try {
$sql = 'DELETE FROM author WHERE id = :id';
$s = $pdo -> prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
Because the $_POST['action'] is not 'Delete' anymore.
I think the condition if(isset($_POST['action']) and $_POST['action'] == 'Yes') must be outside the if(isset($_POST['action']) and $_POST['action'] == 'Delete').
I have a form that generates multiple buttons based on a MySQL Table. All buttons have unique id and names. How can I check if any of the buttons are pressed and then check which button is pressed and based on it perform some action. Below is the logic I want to achieve :
<div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
$dbhost=DB_Host;
$dbuser=DB_User;
$dbpass=DB_Pass;
$dbname=DB_Name;
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (any button pressed)
{
if($_POST['aButton'])
{
$_SESSION['hello']=1;
// big logic here
}
if($_POST['bButton'])
{
$_SESSION['hello']=2;
// big logic here
}
}
else
{
$selectquery="SELECT * FROM systems";
$result=mysqli_query($conn,$selectquery);
$rowcount=mysqli_num_rows($result);
if ($rowcount>=1)
{
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
?>
<button id="<?php echo $row['type']."Button"; ?>" name="<?php echo $row['type']."Button"; ?>" >Select</button>
<?php } } } ?>
</form>
</div>
You can do something like that.
Here is the form
<form action="process.php" method="POST">
<button name="first" type="submit" value="1">First</button>
<button name="second" type="submit" value="1">Second</button>
</form>
Give the buttons different name attribute.
Now when you click any of these buttons it submit the form to process.php
In process.php you can check which button was pressed by checking the name of submitted button like this:
if( isset($_POST["first"]) and $_POST["first"] == 1 ) {
// First button was pressed
}
if( isset($_POST["second"]) and $_POST["second"] == 1 ) {
// Second button was pressed
}
You will need to adjust this code to your needs but it should do the trick
im trying to make something, and now i came to the part where i created a button that should lock the topic, but i don't know how to make it work like submit form, when i press it it should lock the topic, but nothing happens:
echo '<br><div class="ticket_info">';
if($stanje == 0 ) {
echo ' <button class="lockticket" name="lockticketbutton">Zatvori</button></a> ';
}
else if($stanje != 0 ) {
echo ' <button class="lockticket" name="unlockticketbutton">Otvori</button></a>';
}
echo '
Postavio: '.$output['Postavio'].' --- ['.$output['Naslov'].']
</div>
</br><div class="ticket_info2">
'.$output['Text'].'
</div>
';
And this is what it should output:
if(isset($_POST['lockticketbutton']))
{
$id = $_GET['id'];
$query = mysqli_query($con, "UPDATE `Dashboard` SET `Status` = '1' WHERE `ID` = '$id'");
if($query)
{
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
else
{
header('location: dashboard.php');
}
}
you can submit the button by using following code
<form action ="your php file name" method ="post">
<button type= "submit" class="lockticket" name="odgovoritiket" >Otvori</button>
</form>
To use a button as Submit you need to put it into form.
Note: according to w3schools:
If you use the <button> element in an HTML form, different browsers may submit different values. Use <input> to create buttons in an HTML form.
i have this php code in my form. I used pdo to get into mysql database and insert data. A simple form where use enters his name, email, comments, and a checkbox. I use this in jquery mobile environment.
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$dbName = 'database';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=$dbName", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec('SET NAMES "utf8"');
}
catch(PDOException $e)
{
echo "Sorry, you are experiencing server Error: ".$e->getMessage();
exit();
}
if(isset($_POST['sendEmail']))
{
try
{
$senderName = $_POST['sendName'];
$senderEmail = $_POST['sendEmail'];
$comments = $_POST['comments'];
if (isset($_POST['offer'])) {
$offer = 1;
} else {
$offer = 0;
}
$dateTimeSent = date('Y-m-d H:i:s');
$q= "INSERT INTO comments(sendName, sendEmail, comments, offer, dateTimeSent) VALUES (:sendName, :sendEmail, :comments, :offer, :dateTimeSent);";
$query = $dbh ->prepare($q);
$results = $query->execute(array(
":senderName"=>$sendName,
":senderEmail"=>$sendEmail,
":comments"=>$comments,
":dateTimeSent"=>$dateTimeSent,
":offer"=>$offer,
));
}
catch (PDOException $e)
{
$error = 'Error adding elements to database: ' . $e->getMessage();
include 'error.html.php';
exit();
}
exit();
}
?>
This is the form I use:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST" name="comments" id="comments">
<div data-role="fieldcontain">
<label for="sendName">From: </label>
<input type="text" name="sendName" class="validate[required"] id="sendName" data-clear-btn="true" placeholder="Enter name" required >
</div>
<div data-role="fieldcontain">
<label for="sendEmail">Email: </label>
<input type="email" name="sendEmail" id="sendEmail" class="validate[required,custom[email]]" data-clear-btn="true" placeholder="valid_email#true.com" required >
</div>
<label for="comments"></label>
<textarea name="comments" id="comments" value="comments"></textarea>
<label for="offer">
<label for="offer">
<input name="offer" type="checkbox" id="offercheckbox">Please check</label>
</label>
<input type="button" name="Send Email" value="Submit" id="suggestSubmit" onclick="submitForm()">
</form>
My problem is I am trying to figure out how to clear the form fields after a successful submission. I found an option of using Jquery onclick function. I inserted this code before the end of form tag:
<script>
function submitForm() {
$('form[name="comments"]').submit();
$('input[type="email"], textarea').val('');
$('input[type="text"], textarea').val('');
}
</script>
However, if the form was submitted but failed in the jquery validation, all the fields will been cleared even if the submission failed due to but not limited to form validation. So the user when fixing his errors has to reenter all data in all the form fields again. Not good.
I checked the other answers here and other online sources, but i cant seem to make it work.
What`s is the best approach in clearing form fields after a successful submission, if I use PHP-PDO in jquery mobile?
PS. I am a newbie. Thanks.
After a successful submission do http redirect to the form page using header function, this is a pretty new request which should view forms elements in the page with empty status, just like the user is visiting this page for the first time.
It would also be nice to view a success message for the user when opening this page in order to get the sense that his previous request has been processed successfully.