Deleting from table if check box unticked - php

This is probably an easy one but I am stuck. I have a form with checkboxes that show employees and there skills, these are taken from a table with a many to many relationship.
The below code works for updating the records but I am unsure on how to delete records if the checkbox is un-checked
$emp=$_POST['emp'];
if(isset($_POST['chk1'])){
$checkbox=$_POST['chk1'];
$arr_num=count($checkbox);
$i=0;
while ($i < $arr_num)
{
$qry = "INSERT IGNORE INTO skillsets (skill_id, empr_id )VALUES(?, ?)";
$stmt = $mysqli->prepare($qry);
$stmt->bind_param('ii', $checkbox[$i], $emp);
$stmt->execute();
$i++;
}
}
else .... delete from .....
I am not sure of the syntax for the else, can someone help me out?

You can define hidden inputs for every checkbox (before it) with the same name. Eg.
<input type="hidden" name="items[1]" value="no" />
<input type="checkbox" name="items[1]" value="yes" />
1 is your item ID.
And now if checkbox is checked then its value will be send. In other case, value from hidden field will be send to your server. With this data you can iterate through items array, get ID from index and check value to know if it's checked or not.

Related

SQL insert from variable amount of HTML check boxes

I have a user input with checkboxes. The number of checkboxes can vary in quantity because they are generated with a fetch. I would like to transfer the respective value per selected checkbox into a table and create a row for each selected checkbox. My problem is that with my current code only the value from the last checkbox is taken. Not sure how to implement a foreach here.
My code currently looks like this:
HTML Checkbox example which can repeat from 1 to unlimited. Name is always the same but value and id is changing:
<input type="checkbox" class="custom-control-input" name="questionaire_id" id="100" value="100">
<label class="custom-control-label mb-3" for="100"> Some_Name - 100 </label>
PDO Query PHP
if (isset($_POST['speichern'])) {
$questionaire_id = $_POST['questionaire_id'];
$statement = $pdo->prepare("INSERT INTO audit_bundles(questionaire_id) VALUES (:questionaire_id)");
$result = $statement->execute(array('questionaire_id' => $questionaire_id));
}
I have found a solution which works for me. It is taking the value from a selected checkbox and is creating a row. Does not matter how many check boxes i have.
if (isset($_POST['speichern'])) {
$statement = $pdo->prepare("INSERT INTO audit_bundles (questionaire_id) VALUES (?)");
$statement->bindParam(1, $questionaire_id);
foreach ($_POST['questionaire_id'] as &$value) {
// insert row
$questionaire_id = $value;
$statement->execute();
}

Inserting ids of checkboxes in database with php

I have two input fields:
<input type='hidden' name='amenId[]' value='$amen[amenId]'>
<input type="checkbox" name='amentities[]' id='check'>$amen[amenBG]
These two input fields are in foreach tag which loops through an array($amen). After the form is submitted I have php file that loops through the array and insert the id of the checked input and the value. Now the problem comes from the fact that my input fields are checkboxes. I have used this technic for different array where the input type was text and I didn't have problems. Here I have around 30 choices to choose from and when I check the first one and the fifth one in the database where the ids of the choicse should be 1 and 5 but instead of that are 1 and 2. I'm not sure why is that but I'm thinking that it has to do with getting the values only from the checked boxes.
My php code:
$checkedAmen = '';
foreach ($_POST['amentities'] as $key => $amen) {
$checkedAmen = $amen;
$checkedId = $_POST['amenId'][$key];
if ($checkedAmen == "on") {
$checkedAmen = "Yes";
}elseif($checkedAmen == "") $checkedAmen ="No";
$sqlAmen = "INSERT INTO ObjectAmen(ProductId, AmenId, AmenData) VALUES(?, ?, ?)";
if ($stmtAmen = $db -> prepare($sqlAmen)) {
$stmtAmen -> bind_param('iis', $last, $checkedId, $checkedAmen);
}else{
echo "Error: " . $db->error;
}
$stmtAmen -> execute();
}
Can someone help me? I would like to have the correct ids correspoding to the checked choices in the database.
There's nothing currently tying both of your inputs together. You can have a value on a checkbox though, so if it's checked you have the id
<input type="checkbox" name='amentities[]' value='$amen[amenBG]'>
Also you want to take id's off the input if it's in a foreach, because you'll be rebinding the id every time.

Trying to copy data to a table with checkboxes, a form, and php

My webpage is pulling data from two tables - applications and archiveapps - and displays them using the following:
$sql = "SELECT * FROM applications";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Lots of info, including some html thrown in for style."
I want users to be able to click a checkbox listed next to each row and then hit an "Archive Selections" button that then moves all the selected entries from the applications table to the archiveapps one.
So far I've tried a form with it's code half in the echo above (so that a checkbox would go by each listed row from the $sql query) with the submit button outside (so that there would only be one "Archive Selections" button) but I'm sure this isn't proper syntax.
To actually move the data, I had this for the checkbox:
<form method='post' action=''><input type='checkbox' name='archname' value=".$row["charname"].">
(The above was inside an echo statement, so I assume it was able to pull the $row["charname"] no problem, but am unsure how to verify that.)
A little further down the page is the submit button and </form>.
And then I've got the function I want it to run when the submit button is clicked, to check if boxes have been selected and copy them into the archiveapps table. I'm sure there's something I'm missing here, probably in referencing what exactly is selected, and then copying that row's data to the other table... but honestly I just don't know enough about php to know what I'm missing.
if(!empty($_POST['archname'])) {
foreach($_POST['archname'] as $check) {
function archiveapp() {
$sqli="INSERT INTO archiveapps SELECT * FROM applications";
if ($conn->query($sqli) === TRUE) {
echo "<i>Archived</i>";
} else {
echo "Error: " . $sqli . "<br>" . $conn->error;
}}}}
Most of this has just been gathered from google searches and kind of mushed together, so I'm sure there are a lot of things done wrong. Any pointers or advice would be greatly appreciated!
Oh and my end goal is to copy the data to the archiveapps table and then delete it from the applications table, but for now I've just been focusing on the copying part, since I assume deleting a row will be fairly simple? Either way it's not the priority for this question.
Thanks in advance for any help!
Use a tool like FireBug to see what you are actually posting to server. You have multiple checkboxes with the same name, so you are sending only 1 value (the last checked, I think).
You need to send all of them, so use brackets after the name:
<!-- this is just an example -->
<input type="checkbox" name="archname[]" value="1">
<input type="checkbox" name="archname[]" value="2" checked>
<input type="checkbox" name="archname[]" value="3" checked>
Then on PHP, inside $_POST['archname'] you will get this:
Array(2, 3)
After this, you can do a foreach(...) loop like you are already doing, inserting only the ID you get from the $_POST variable:
foreach($_POST['archname'] as $id){
$sqli = "INSERT INTO archiveapps (id) VALUES (".(int)$id.")";
}

how do you store multiple rows and column array in mysql

I have an array of checkboxes.
<input type="checkbox" name="selection[]" value="move" />
<input type="checkbox" name="selection[]" value="move2" />
<input type="checkbox" name="selection[]" value="move3" />
<input type="checkbox" name="selection[]" value="move4" />
Depending on the number of checkboxes selected, a table with corresponding number of rows is generated.
for($x=0; $x<$N; $x++)
{
echo nl2br("<td><textarea name=art[] rows=10 cols=30></textarea> </td><td><textarea name=science[] rows=10 cols=30></textarea></td></textarea></td><td><textarea name=method[] rows=10 cols=30></textarea></td><td><textarea name=criteria[] rows=10 cols=30></textarea></td></tr>");
}
I cannot tell how many table rows with corresponding columns will be generated each time. So how to write the code to insert each set of row array is a problem. I have tried the
$optionsVal = implode(",", $data);
but that only works to store the selected options and not for the generated table rows and columns.Please can anyone help with this. Thanks in advance
Okay so I think I understand a little better, but perhaps you should relay your question in other terms.
Basically my understanding is that you are accepting an uncertain (within the boundaries of the number of checkboxes you have) number of checkboxes, which there in turn generate a row for each selected check box.
If you want to store these generated rows in mySQL you need to post the data back to the database
$result = mysqli_query($query, $conn);
$row = mysqli_fetch_array($result);
You need to set a $result similar to this, and store your check box values in it
In this example if the end-user hits the save button it inserts the values from the check box into a variable
if(isset($_POST["savebtn"]))
{
//inserting the new information
$id = $_POST[""];
$name = $_POST[""];
//iterate through each checkbox selected
foreach($_POST["checkbox"] as $loc_id)
{
$query = "INSERT INTO table(ID, Loc_Code) VALUES('$id', '$loc_id')";
$result = mysqli_query($query, $conn);
}
?>
This was just kinda taken from another example, but you are way off with the implode, you need to save the results of the php selection to variables first, and then assign them rows in mySQL by looping through the selection
UPDATE:
Okay, so you got them in an array, seelction[] - this is good now you would want to check to see if a certain value is selected...
if (in_array("move2", $_POST['selection'])) { /* move2 was selected */}
then you want to put that into a single string - you were right with the implode method
echo implode("\n", $_POST['selection']);
then echo it out with a foreach loop
foreach ($_POST['selection'] as $selection) {
echo "You selected: $selection <br>";
}

Generate a query that changes a single element on multiple rows PHP MySQL

I'm working on a homework assignment that involves PHP. Basically, I have a page that contains a web form that renders items pulled from a database. There's checkboxes on each row and 2 radio buttons. The user selects "accept" or "deny" and when submit is clicked, the items that are checked are supposed to change to that approval status. All of the items in the form are submitted into post. I thought that post is an array so I could just use a while loop with a counter so that the loop traverses through the array and when it gets to the last index (which should contain approve or deny). A query is generated that changes all of the previous indexes to approve or deny. I'm sorry if this isn't making much sense.
Here's a picture for more clarification
Here's the code I used to generate the webform:
<?php
#create a query string
$query = "SELECT * FROM Request WHERE superemail = '$user'";
#echo $query;
#run the query
$result = mysqli_query($link, $query) or die('error querying');
while($row = mysqli_fetch_array($result)){
#print out each row of the queryi
#line up the query results with temporary strings
$change = $row['KEY'];
$name = $row['first']. " " . $row['last'];
#echo $name;
$email = $row['email'];
#echo $email;
$type = $row['type'];
#echo $type;
$duration = $row['duration'];
$status = $row['status'];
#create a table row with the query results
echo "<tr><td><input type=checkbox name=$change /></td>
<td>$name</td>
<td>$email</td><td>$type</td>
<td>$duration</td><td>$status</td></tr>";
} #end while
?>
<label for=update>Change status to:</label><br />
<input type=radio name=update value=A />Approved<br />
<input type=radio name=update value=D />Denied<br />
<input type = submit value = "Change Status" />
Each input tag (your checkboxes and your radio button) in your html should have a name attribute, such as: <input type='radio' name='accept' value='1' />. When the form is submitted and processed by PHP, your script will be able to access that info at $_POST['accept'] (or $_GET['accept'] depending on the form's method).
So you should be able to specify a name for the radio button, then check to see if there is a value in the POST array at that index.
I am going to assume a few things. First, that it is a design goal of yours to only process items in your approval queue that you choose to select, leaving the others alone. Second, that you want to change their status to what is chosen in a radio button. Third, that you want both a code snippet and an explanation as to how the task got accomplished.
So, here goes.
You have a series of checkboxes; I assume they have the same name. If you wish for the values to be passed to PHP as an array, you absolutely need to name the inputs whatever[] with emphatic emphasis on the []! This is what creates an array from the checkbox to appear in the $_POST/$_GET. Only those items selected will appear in the array. The value ought to be something useful (A value in the corresponding database table, say) which you can select for and query on...after sanitizing the input, of course.
So, your HTML input tag should look like this:
<input type="checkbox" name="process[]" value="<?php echo $employeeName ?>" >
You should have this coming back at you...
$_POST['process'][array(0=>name1, 1=>name2/*...etc*/)]
...which you can loop through with a foreach at your leisure.

Categories