Checkbox insert 1 or 0 into SQL database - php

I am setting up a system that has many answers from a question. Therefore the user can click a button to dynamically add answers. I want the user to be able to tick a checkbox next to the answers which are correct and then insert this into the database (1 being correct).
Here is what I have:
HTML:
<div id="answers">
<label class="answer">
Answer:
<input type="text" name="ab_name[]" value=""/>
Correct?
<input type="checkbox" name="ab_correct[]" value="0">
</label>
</div>
PHP
$ab_name = $_POST['ab_name'];
$ab_correct = $_POST['ab_correct'];
$sql = "INSERT INTO answers_bank (`ab_name`, `ab_correct` ) VALUES (:ab_name, :ab_correct )";
$stmt = $db->prepare($sql);
foreach ($_POST['ab_name'] as $ab_name) {
$stmt->bindValue(':ab_name', $ab_name);
$stmt->bindValue(':ab_correct', $ab_correct);
$stmt->execute();
}
Like this:
The SQL inserts the ab_name but the ab_correct is ALWAYS set to 1 if it is ticked or unticked. Any guidance on this please?

You could use a for loop instead of the foreach. Well, first of all, you need to make sure both arrays has the same amount of elements.
if(count($_POST['ab_name']) != count($_POST['ab_correct']))
exit('Not same amount of elements.');
Then, loop through each of them.
for($i=0; $i<count($_POST['ab_name']); $i++){
$stmt->bindValue(':ab_name', $_POST['ab_name'][$i]);
$stmt->bindValue(':ab_correct', $_POST['ab_correct'][$i]);
$stmt->execute();
}

if(isset($_POST['$ab_correct'])){$update = 1;}else{$update = 0;}
foreach ($_POST['ab_name'] as $ab_name) {
$stmt->bindValue(':ab_name', $ab_name);
$stmt->bindValue(':ab_correct', $update);
$stmt->execute();
}

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();
}

PHP foreach Construct Confusion

I am having a hard time wrapping my head around the foreach construct. I have found numerous examples of course, but I never seem to be able to adapt them to my needs.
Please consider this working example I have:
I am collecting two dates in an HTML form:
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" name="FirstAGMDate" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" name="MinutesInspectedFromDate" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
On submit the values are being pushed to the mysql database with a PDO prepared statement:
if (isset($_POST['submit'])) {
$sql = "UPDATE jobsinglevalues SET Date = :FirstAGMDate WHERE FormId = 0;
UPDATE jobsinglevalues SET Date = :MinutesInspectedFromDate WHERE FormId = 1;";
$sth = $db->prepare($sql);
$sth->execute(array(':FirstAGMDate'=>($_POST['FirstAGMDate']), ':MinutesInspectedFromDate'=>($_POST['MinutesInspectedFromDate'])));
}
This works no problem, but it's not very clever when I need to repeat this for a dozen inputs. What I want to do is achieve this with only one line of sql; looping for each <input type="text" name="Value" />.
How can I place this into a foreach loop?
In my head it works like this:
On submit each input updates the value in the database based on FormId, which increments by 1 each loop starting at 0. FormId is not a primary key, it simply mirrors the order in which the form elements are displayed.
Update - working example
if (isset($_POST['submit'])) {
$FormId = 0;
foreach($_POST['Value'] as $avalue){
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId";
$sth = $db->prepare($sql);
$sth->execute(array(':Value'=>($avalue), ':FormId'=>($FormId)));
++$FormId;
}
}
This seems to logically work to me! Is the correct solution similar? Please let me know if I need to clarify anything.
Thankyou,
Sam
Let's start by making sure all our values are in an array after posted; if you don't care about the keys you can just use name="Values[]", but I'll use name="Value[FirstAGMDate]" etc so we know what key a value belongs to.
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" id="FirstAGMDate" name="Value[FirstAGMDate]" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" id="MinutesInspectedFromDate" name="Value[MinutesInspectedFromDate]" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
Now we can process the posted array of values. If we want to do something with the key, we can use foreach($_POST['Value'] as $akey => $avalue), if we are only interested in the values then foreach($_POST['Value'] as $avalue) suffices.
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId;";
$sth = $db->prepare($sql);
foreach($_POST['Value'] as $akey => $avalue) {
$sth->execute(array(':Value' => $avalue, ':FormId'=> $FormId ));
++$FormId;
}
[edit] As per edit-suggestion by #AravindKishore, creating the prepared statement is better done before the loop. Prepare once, enjoy forever.

Deleting from table if check box unticked

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.

Add another item/row on form, insert into DB

These two fields are inserted into a database. However, I want to give the user the ability to "Add another item". They should be able to, ideally, add as many items as they like. When they submit the form, the data would be inserted into a mysql table.
How can I go about doing this? Creating 10 extra columns in my database to accommodate extra items being added does not sound realistic nor ideal.
Thanks for the help!
Here is a snippet of my code, where I insert my data into the DB:
if ($stmt = $mysqli->prepare("INSERT items (number, description) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $number, $description);
$stmt->execute();
$stmt->close();
}
This is a pretty complex question, but there are some pretty straightforward solutions. First off, you'll need to change the back-end PHP script that you use to handle having a variable number of items.
For example, right now, you probably have something like:
$item_number = $_POST['item_number'];
$item_description = $_POST['item_description'];
add_item_to_db($item_number, $item_description);
You'll need to change your code to handle the processing of an array of items:
$item_numbers = $_POST['item_number'];
$item_descriptions = $_POST['item_description'];
// validate that count($item_numbers) == count($item_descriptions)
for ($i = 0; $i < count($item_numbers); $i++) {
add_item_to_db($item_numbers[$i], $item_descriptions[$i]);
}
There's quite a bit of error handling that you'll need to perform above that's not shown. If the user enters a different number of item_numbers than item_descriptions, you'll have to determine how to handle that. Also, any of the fields may be blank. Some cases may be errors, others perhaps not.
You'll have to change your HTML:
<input type="text" name="item_number[]" />
<input type="text" name="item_description[]" />
Note the [] in the name. That specifies an array of values for each.
Finally, you'll need to dynamically add a new set of input items on the screen when the user presses the Add another item link. I would recommend using jQuery for this. To accomplish this you would do something like:
jQuery('<input type="text" name="item_number[]" /><input type="text" name="item_description[]" />').appendTo('#someDiv');
Ensure that the new input elements are appended inside the form element. Obviously, there is a lot of code left to be written. This is just a basic example of the concepts.
Just use :
name="item[]"
for item # '
and
name="description[]"
<input type="text" name="item[]" /><input type="text" name="description[]" />
For item description field and in your server side iterate through both of them.
in the front end just create a script that duplicate that node many times.
EDIT
Based in the code you showed it should be something similar to the below code :
if(isset($_POST['item']){
for($i = 0; $i < count($_POST['item']); $i++){
$number = $_POST['item'][$i];
$description= $_POST['description'][$i];
if ($stmt = $mysqli->prepare("INSERT items (number, description) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $number, $description);
$stmt->execute();
$stmt->close();
}
}
In your javascript do like below:
function addRow(){
document.getELementById('container').el.innerHTML += '<input type="text" name="item[]" /><input type="text" name="description[]" />' ;
}
HTML Code:
<form name='myform' >
<div id="container">
<input type="text" name="item[]" /><input type="text" name="description[]" />
</div>
<p onclick="addRow() ;" >Add another item</p>
</form>
I hope this helps.
UPDATE
Try this one :
if(isset($_POST['item']){
if ($stmt = $mysqli->prepare("INSERT items (number, description) VALUES (?, ?)"))
{
for($i = 0; $i < count($_POST['item']); $i++){
$number = $_POST['item'][$i];
$description= $_POST['description'][$i];
$stmt->bind_param("ss", $number, $description);
$stmt->execute();
}
$stmt->close();
}

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

Categories