PHP deleting multiple rows with checkboxes - php

I have a form that includes a delete button. I want the user to be able to select all the items they wish to delete at once.
I managed to get the echo to display but the items still remain on the page. Can you please point out why that happens? Any help is appreciated!
Delete button:
<input name="del_btn" type="submit" value="Delete">
The check:
if (isset($_POST['del_btn']) && $_POST['del_btn']){
for($i = 0; $i < count($_POST['checkbox']); $i++){
if (isset($_POST['checkbox'])) {
mysql_query("DELETE FROM `posts` WHERE `id` = '" . $_POST['checkbox'][$i] . "' LIMIT 1");
echo 'deleted';
}
}
}
the items' checkbox:
<input name="checkbox[]" type="checkbox" id="<?php echo $id; ?>" />

This really depends on how variables are defined in your controller, and how they are displayed in your view file.
If you want to hide/clear the values in your forms you can:
Reload the page: create a redirect at the end of your if (isset($_POST['del_btn']) && $_POST['del_btn']){ statement that sends the user back to the new page.
Use jQuery to hide divs where the checkbox is checked.
Redefine variables in your controller after the post to be NULL.
Add a ternary operator to your values in the view so for example <input name="form_input" type="text" value=<?=isset($_POST['del_btn'] ? NULL : $form_input?>> which means that the form will display as NULL when the del_btn is submitted.

<input name="checkbox[]" type="checkbox" id="<?php echo $id; ?>" />
I think you must put something like
<input name="checkbox[]" type="checkbox" value="<?php echo $id; ?>" />
Note the word "value" instead of "id". You are putting the ID in the id attribute. It is to assign a specific target if you want to take the value. (You can use Javascript or JQuery to do this).
In your case, use the tag "value" to ensure that you have correct ID value for your check box. Echo the query and not the word "deleted".
$queryDel = "DELETE FROM posts WHERE id = " . $_POST['checkbox'][$i] . " LIMIT 1";
echo $queryDel;
Please beware of SQL Injection if you are using mysql_query(). Use mysqli instead. Use prepared statement to prevent it or at least provide some white list or validation.
Hope this helps. Thank you.

<input name="checkbox[]" type="checkbox" value ="<?php echo $id; ?>" id="<?php echo $id; ?>" />
Try this it will work. and check the value print_r($_POST) you will able to see all the post value and able to get right value.

When you are using checkbox your element became an array than you can use multiple approaches:
Use ajax (example with jQuery) to avoid submit:
<script>
$(document).ready(function() {
$('[name="del_btn"]').click(function() {
$.post('/my/action.php', $('form').serialize(), function(r) {
if (r.success) {
alert('deleted....');
} else {
alert('error');
}
},'json');
return false; // prevent submit
});
});
</script>
Than you can simplify your code with this:
<?php
if (isset($_POST['checkbox']) && count($_POST['checkbox'])){
$c = implode(',', array_map('intval', $_POST['checkbox'])); // sanitize data
$r = mysql_query("DELETE FROM `posts` WHERE `id` IN(" . $c .")");
echo json_encode(array('success' => $r));
}

Related

Multiple forms and multiple submissions with one submit button

At the moment, I'm using a loop to read the 'questions' and 'answers' fields from my postgresql "PDPC".considerations table and reflecting them on the form. I'd like to update them all with one submit button.
I refered to PHP MySQL Multiple Forms and Multiple Submits on single page and tried using the <input type="hidden">, arrays and while loop but the form either does not execute or it does not correctly update all the forms.
I think the error is around the $_POST (at the top) and the HTML form (at the bottom). (Sorry if the codes are messy, it is my first time with PHP, HTML and Postgres). Thank you!
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$question = $answer = "";
$question_err = $answer_err = "";
// Processing form data when form is submitted
if(isset($_POST["consideration_no"]) && !empty($_POST["consideration_no"])){
$counter = 0;
// Get hidden input value
//$consideration_no = $_POST['consideration_no'];
$dg_no = $_POST['dg_no'];
$consideration_no = $_POST['consideration_no'];
$answer = $_POST['answer'];
// Check input errors before inserting in database
if(empty($answer_err)){
while ($counter<5){
// Validate address address
$input_answer = trim($_POST["answer"]);
if(empty($input_answer)){
$answer_err = "Please enter an answer.";
} else{
$answer1[$counter] = $input_answer;
}
// Prepare an update statement
$sql = 'UPDATE "PDPC".consideration SET answer=:answer WHERE consideration_no = :consideration_no';
if($stmt = $pdo->prepare($sql)){
$stmt->bindParam(":answer", $param_answer);
$stmt->bindParam(":consideration_no", $param_consideration_no);
//Set Parameter
$param_answer = $answer1[$counter];
$param_consideration_no = $consideration_no[$counter];
// Attempt to execute the prepared statement
$stmt->execute();
$counter++;
}
}
if($stmt->execute()){
// Records updated successfully. Redirect to landing page
header("location: home1.php?dm_no=".$_GET["dm_no"]);
exit();
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
// Close connection
unset($pdo);
} else{
// Check existence of dg_no parameter before processing further
if(isset($_GET["dg_no"]) && !empty(trim($_GET["dg_no"]))){
// Get URL parameter
$dg_no = trim($_GET["dg_no"]);
// Prepare a select statement
$sql = 'SELECT * FROM "PDPC".consideration WHERE (dg_fkey = :dg_no AND code_no = 1)';
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":dg_no", $param_no);
// Set parameters
//$param_no = $dg_no;
$param_no = trim($_GET["dg_no"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() > 0){
SubSection($subsection1_1); //Collection Purpose Section
while($row = $stmt->fetch()){
// Retrieve individual field value
$consideration_no = $row["consideration_no"];
$question = $row["question"];
$answer = $row["answer"];
echo "<a href='considerationupdate.php?consideration_no=". $row['consideration_no'] ."' title='Update Data Map' data-toggle='tooltip'><span class='glyphicon glyphicon-pencil'></span></a>";
//...time to show the questions and answers with the while loop...
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="answer1[]" id = "$answer1" value="<?php echo $answer; ?>"/>
<input type="hidden" name="consideration_no[]" id = "consideration_no" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
<?php
}
?>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
unset($stmt);
// Close connection
unset($pdo);
}
else{
// URL doesn't contain dg_no parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
It should read the questions and answers from the DB table, show it on the forms as the label and text fields (working), and the user should be able to update the form after editing the text fields and clicking submit (Not working properly).
Since is your form and you are using SQL to get and the objective is to update the data with one submit?
Why not just use one form?. I belive you can do all you need with just one and multiple input.
Your branch if(isset($_GET["dg_no"]) && !empty(trim($_GET["dg_no"]))){ depends on get parameters, however, your <form method="post"> of <input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/> uses post parameters.
Therefore the branch will never be executed unless the page is requested by another GET-request like a link or another form.
If the parameters can occur in both methods, POST and GET as well, you might want to check the $_REQUEST array instead. Be aware that the parameters listed in $_REQUEST can vary depending on the .ini settings request_order and variables_order.
According to your comment 'Because each form is for one table row.' in another answer, this might be an XY problem.
Consider to take the common way not generating multiple forms but array parameters similar as you did in
<input type="hidden" name="answer1[]" id = "$answer1" value="<?php echo $answer; ?>"/>
Here you rely on keys getting generated automatically. As well you can specify an individual key:
<input type="text" name="some_parameter[<?php echo $answer; ?>]">
Further more
There is an HTML line in the loop having a static id on an element:
<input type="hidden" name="consideration_no[]" id="consideration_no" value="<?php echo $consideration_no; ?>"/>
This will not break PHP, however, it is against the HTML specs saying an id has to be unique per document.
I have fixed the issue! It was the logical flow of the script. Specifically, the POST variable at the top should be changed to dg_no, add the dg_no parameters along with it, loop the parameters instead of the entire preparation script and include the execute script in the whie loop too.
Thanks for the help and guidance, they were much appreciated!

PHP retrieving variables from a large SQL result set

I have been working on my own PHP project. I have hit an obstacle. I am trying to retrieve the results of a database and print out a form for each result set.
I then wish to interact with one particular result either be deleting it or passing it into a function etc..
Heres is my current code :
<?php
while($row = mysqli_fetch_array($result)){
echo '<div id="post">'; ?>
<form action="" method="post">
<?php
echo "<font size=4>".$row['post']."<br>";
echo "posted by : ".$row['username']."<br>";
$id = $row['p_id']; ?>
<input type="submit" name="choice" value="Y">
<input type="submit" name="choice" value="N">
</form>
<br>
</div>
}
<?php
if($_POST['choice']=="Y"){
// progress
functionA();
}
else if($_POST['choice']=="N"){
// delete or remove
functionB();
}
?>
So my goal here would be click Y to progress that particular result or N to delete/remove the result.
However currently by clicking either button all results either get deleted or progress. I do know that the id should be used to differentiate between posts but I cant quite seem to get it to work. Once the button is pressed it passes all results to either function.
First of all, I suppose you want to know the record to delete. So, add an input to your form:
<input type="hidden" name="id" value="<?php echo $row['p_id']; ?>">
Then, in your script, call:
if( $_POST['choice'] == "Y" )
{
// progress
functionA( $_POST['id'] );
}
elseif( $_POST['choice']=="N" )
{
// delete or remove
functionB( $_POST['id'] );
}
Additional problem: how you can use your db connection inside the functions? Assuming your mysqli connection is named $conn, call the function(s) in this way:
functionA( $_POST['id'], $conn );
Side note: First process $_POST values, then retrieve db records and print it.
Side note 2: take a look at prepared statement.
Read more about variable scope
Read more about prepared statements
Use two different <input type="radio">s for each item with the id in the value and let the user select which to delete and which to process.
So for an item with id 1 the outputted HTML would look like:
<input type="radio" name="items[1]" value="delete"><input type="radio" name="items[1]" value="process">
The name forces the items to go to _POST as an array with the ids as keys and the selected action as their values.
Example html: https://jsfiddle.net/gu1gkwod/

How to auto submit a checkbox

Here is HTML/JavaScript:
<form method = "post" style="display: inline;" name="thisform<?php echo $employee->id; ?>">
<input type="hidden" name="user" value="<?php echo $employee->id; ?>" />
<input type="hidden" name="auto" value="<?php echo $employee->stay_live; ?>" />
<h3><input type="checkbox" name="stay_live" onclick="document.forms.thisform<?php echo $employee->id; ?>.submit();" <?php if ($employee->stay_live == '1') { echo "checked"; } ?> title="Click to Stay Live Every Day" /> <?php echo $employee->name; ?>
</form>
Here is PHP:
<?php
if(isset($_POST['stay_live'])) {
$user=$_POST['user'];
$auto=$_POST['auto'];
if ($auto == 1) {
$sql = "UPDATE users SET stay_live = 0 WHERE id = '{$user}';";
}
if ($auto != 1) {
$sql = "UPDATE users SET stay_live = 1 WHERE id = '{$user}';";
}
mysqli_query($dbconnection, $sql);
}
?>
If you see the onclick code in the form, it will auto-submit form and do PHP POST. However, the onclick only works if the checkbox is NOT checked. If it IS checked, the screen does refresh, as if it did thing, but the POST is never submitted.
So to summarize; everything works as expected when the box is not checked and it needs to be set. But to UNSET it, the server function is never called. Can anyone see why?
note: this is test code, so please no comments on sql injection
Checkbox values are not sent when they are unchecked, so $_POST["stay_live"] is not set.
<?php
if (isset($_POST["user"])) // type="hidden" will be sent regardless of checkbox
{
if (isset($_POST["stay_alive"])) echo "Checkbox checked";
else echo "Checkbox not checked";
}
?>
Using Jquery I'd do the following: You need to make a file with the functions that you want to be executed. This file will receive via POST or GET
To your onclick attribute just add an if for your action variable, if(element checked) action = unchecked --- else action = check
--Jquery function
function cBoxSubmit($employId, $action){ // call it in your onclick attribute.
$.post("submitFunction.php",{action: $action, employId: $employId, ...},function(data){ // Parameters: URL file, variables which will receive, call back function
if(data){
// On Success or in your case if checked
// add some code if needed
}
else{
// If unchecked
// add some code if needed
}
}
}
NOTE: echo == return in your php file ... This is how you return data to the call back function in your Jquery function

Update checkbox data in SQL-database with PHP

As the title reveals I got an issue with how to update a checkbox that already has data in my SQL database.
My code looks like following:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name <input type"text" name="inputName" value="<?php echo $hemsida['Namn']; ?>" /> </br>
Commentar <input type"text" name="inputComment" value="<?php echo $hemsida['Comment']; ?>" />
<br/>
</br><input type="checkbox" name="inputAll" value="checked" <?php echo $hemsida['All']; ?>/>Alla
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
<input type="submit" name="submit" value="Redigera">
<?php
if(isset($_POST['submit'])) {
$u = "UPDATE hemsida SET `Namn`='$_POST[inputName]', `Comment`='$_POST[inputComment]', `ALL`='$_POST[inputALL]' WHERE ID = $_POST[id]";
mysql_query($u) or die(mysql_error());
echo "User has been modified";
header("Location: ..//sokh.php");
}
?>
The echo $hemsida['Namn'],['Comment'], and ['All'] just brings up and shows the old data thats in the database, but I do not understand what to do to update the checkbox. I have looked everywhere but I am stuck. Thank you in advance!
If I understand your question correctly, you are looking for a way to have a checkbox be either checked or not checked depending on database info. If so, I would try something like this. At the top of your code where you get your database info, put
if($conditionForCheck){
$inputAll = ' checked="checked"';
}
Then in your form
<input type="checkbox" name="inputAll"<?php echo $inputAll; ?> />
your question is not clear but i think you have a column in your database named "all" ? and perhaps this column can take only 1 value (true or false) !!
then you can test this value in your form, if the value is true : checkbox will be checked, else : checkbox will not be checked :
<input type="checkbox" name="inputAll" checked="<?php if($hemsida['All'] == true) echo checked; ?>" />Alla
dont use value="", use checked instead, then test value of $hemsida['All'] if it's true echo checked else anything to do
for your php code and server side of your application you can just test if checkbox is checked and then you have choice for what do you want to assign to your column in database, for example if checkbox is checked create a variable (for example $value_of_checkbox) and assign a value ("true" for exampel) to this variable, then include this variable in your sql code for update database column :
if (isset($_POST['inputALL'])) {
$value_of_checkbox = true;
}
else {
$value_of_checkbox = false;
}
if(isset($_POST['submit'])) {
$u = "UPDATE hemsida SET `Namn`='$_POST[inputName]', `Comment`='$_POST[inputComment]', `ALL`='$value_of_checkbox' WHERE ID = $_POST[id]";
mysql_query($u) or die(mysql_error());
echo "User has been modified";
header("Location: ..//sokh.php")
note : i change also sql code in this part : ALL='$value_of_checkbox'

Grabbing specific variable from while loop for form submit

I have a while loop generating information with a checkbox, I would like to update the database with the new "completed" value. How can I select the specific checkbox that is generated. Please help with showing me how I can grab the specific value of a checkbox and the task_name.
Thanks, Ryan
while ($row = mysql_fetch_array($query)){
$task_name = $row['task_name'] ;
$task_description = $row['task_description'];
$task_completed = $row['completed'];
$tasks .= '<div id="tasksBody">
<form action="" method="post">Completed? <input name="completed" type="checkbox" '.
($task_completed == 1?'checked="checked"':'').
' /><input type="submit" value="Update"><br /><br />
<b>'.$task_name.'</b><br /><br />'.$task_description.'<hr><br /></form></div>';
}
}
echo $tasks;
You need to name your input with something unique for the row, such as the task_name, or better, a database record ID.
Then when the user submits the form, you will use $_POST["YourTaskNameOrIDHere"] to check the value.
What you have currently calls all the check boxes the same thing.
EDIT: I'm sorry, you're isolating all of these in their own forms, I just realized that.
What you can add is an <input type="hidden" value="$task_name" name="TaskName" /> to the form, so you can look what the checkbox is corresponding to. Then, when the user submits the form, use $_POST["TaskName"] to find out the name of the task.
Add a hidden field to each of your forms containing the task_id
<form action="" method="post">
Completed?
<input name="completed" type="checkbox" <?=($task_completed == 1?'checked="checked"':'')?> value="1" />
...
<input name="task_id" value="<?=$task_id"?> type="hidden" />**strong text**
</form>
After submit:
if (isset($_POST['task_id']) { // form has been submitted
$task_id = $_POST['task_id'];
$completed = $_POST['completed'];
$sql = "UPDATE task SET task_completed=$completed WHERE task_id=$task_id LIMIT 1";
// code for updating database
// better use PDO or mysqli-* instead of old and deprecated mysql_*
}

Categories