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();
}
Related
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.
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();
}
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.
I have some simple PHP code that will generate new text boxes with the naming scheme of 'car_init$i' and 'car_num$i'. Where $i = 1 and I use i++ to increment it up. The problem I'm having is that while a user can have a maximum of 70 text boxes generated, it can be any number between 1 and 70. So I can have 46 text boxes as an example on a page if the user wanted just 46. So I would have car_num1, car_num2, car_init1, car_init2, etc. as my form names.
Car_ID would be my auto-incremented primary key, and I'd have 2 columns car_num and car_init. Is it possible to do something like this: INSERT INTO dbo (car_init, car_num) VALUES (car_init$i, car_num$i) and then use $i = 1 and i++ to increment it while adding all the values to new rows? Car_id = 1 would contain car_num1 and car_init1 information in their respective columns, Car_id = 2 would contain car_num2 and car_init2 information, and so on and so forth.
EDIT:
So this is the code I have now:
$car_num = $_POST["car_num"];
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
}
What happens is every time I add to my database, only the last thing I entered gets inputted. So if I have 3 cars needed, that's 6 text boxes, but only the last text boxes on the page are the ones that get inputted.
EDIT 2: This is how my text boxes are generated. All text boxes have it the way you said, using the 'car_init[]' and 'car_num[]'.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$i = 1;
while ($i <= $_POST['carAmount'] AND $i <= 70) {
// Now print the text box to the screen
echo "<b>$i</b>. Car Initial: <input type=\"text\" class='element text small' name=\"car_init[]\" maxlength='4' id='car_init[]' /> ";
echo "Number: <input type=\"text\" class='element text small' name=\"car_num[]\" maxlength='6' id='car_num[]' /><br>";
$i++;
}
}
Ah, I think I got it.
This is a problem:
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
}
I assume you're then running the query $sql? If so, that is running only the last value $sql contained! You need to:
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
// actually run the query!
}
Change your html to something like this:
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
Then in php, your variable will be an array!
$_POST['car_init'] // is an array!
Loop through those and do multiple INSERTs.
foreach ($_POST['car_init'] as $car_num => $car_init) {
// "INSERT INTO dbo (car_init, car_num) VALUES ('$car_init', $car_num)"
}
Edit based on your updates:
INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')"
Use PDO with prepared statements instead of using string interpolation. You seem to be susceptible to sql injection attacks.
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>";
}