Insert value of checkbox and number input into database - php

I tried combining two answers from here:
counting how many checkbox are checked php/html
And here:
validating input types "checkbox" and "number" php/html
My goal is to count how many checkboxes were selected, and insert their values along with the number value in the number input.
I found various other posts about it, but couldn't figure out an answer.
Here is the code:
echo '<form action="" method="post">';
Then I have a for loop, where I create my table rows, with the checkboxes.
Where $id = $row[0] is updated on each loop, which is the id equivalent of my entry.
(The output of
echo '<td style="vertical-align: top;">' . $row[0] . '</td>';
Shows the id correctly)
echo '<tr>';
echo "<td style='vertical-align: top;'><input type='checkbox' name='choice[$id][id]' value='$id'></td>";
echo "<td style='vertical-align: top;'><input type='number' name='choice[$id][order]' size='20'></td>";
echo '</tr>';
echo '<b> <input type="submit" value="Insert"></b>';
Then, on the next page, I have this:
$var_checkbox=$_POST['choice'];
$sql_var_id = "SELECT id FROM custom_form WHERE id=(SELECT max(id) FROM custom_form)";
$var_id_result = mysqli_query($link,$sql_var_id);
$var_id = mysqli_fetch_array($var_id_result);
$count=count($var_checkbox[$var_id[0]]);
for($i=0; $i<$count; $i++){
if($var_checkbox[$i]!= NULL){
$sql1 = sprintf("INSERT INTO custom_form_has_property (custom_form_id,property_id,field_order) VALUES ('%d','%d','%d');",
$var_id[0],
$var_checkbox[$var_id[0]][id],
$var_checkbox[$var_id[0]][order]
);
$result1 = mysqli_query($link,$sql1);
}
}
The problem is, that no values of checkboxes or numbers are inserted.
(As a side note, to try and be more specific)
If instead of matrixes, I use
echo "<td style='vertical-align: top;'><input type='checkbox' name='choice[]' value='$row[0]'></td>";
echo '<td style="vertical-align: top;"><input type="number" name="order[]" size="2"></td>';
And
$var_checkbox=$_POST['choice'];
$order = $_POST['order'];
Then
echo "Orders: $order[0],$order[1],$order[2],$order[3],$order[4],$order[5],$ordemr[6]";
echo "Choices: $var_checkbox[0],$var_checkbox[1],$var_checkbox[2],$var_checkbox[3],$var_checkbox[4],$var_checkbox[5],$var_checkbox[6]";
Will output
Orders: 1,,2,,3,,Choices: 1,3,13,,,,
I need the choiced from the checkboxes to be somehow linked to the orders from the number field. And the only way to achieve that, is if they have the same name, but different indexes, which is why I have the matrix, in the first index, it's saved the id number, which is generated on each loop, and in the second, the actual name, which makes the distinction between them (id and order).
I tried various other things, but it all comes back to the same problem...
The value of order (number) is stored into the array, even when null, while the value of choices (checkbox) doesnt.
I could do an array_filter(), but there is no guarantee that the user will not input an order, while not ticking a choice checkbox.
If I would compare the length of choice with the length of order, after filtered, and if they output the same size, there is still no guarantee, that the user didnt check checkbox of line x, and added a value in the order field, on line y.
Maybe there is a way to pass unchecked values to the choice[] variable as null, the same way it happens in order[]?

What is this? choice[.$id.] ? what are the dots for?
I believe this is the bug!
You probably were trying to concatenate $id into the string before and just forgot to remove them?
Corrected line:
echo "<td style='vertical-align: top;'><input type='checkbox' name='choice[$id][id]' value='$id'></td>";

there are some way to do this ..
you have to count total no of selected check box via jQuery and set those value in hidden field at view page on each check box check or on form submit
you have to take counter on insert part and save the ids and at last update ids value with counter value in database ....

Related

How to INSERT multiple rows with multiple values, but only for items that have checkboxes ticked next to them

I am coding a discography tool for a music database.
Artists are able to insert tracks, singles, EPs, and albums all into separate tables on the database.
Having tracks be in their own separate table allows the same tracks to be attached to multiple singles, EPs and albums while only requiring there to be one record for that track in the database.
Which means individual track pages can have an automatically generated list of links back to the Singles, EPs and albums that they appear on. Making navigating the database through the website a much smoother experience.
I have come to the point where I am coding a tool to attach any existing tracks in the database for a given artist onto an album page.
I am using another table in the database called 'trackconnections' to create the relational links between the track ids from the track table and the album id from the album table, with an additional column called albumtracknum available to be able to output the tracks in the right order when queried on the album page.
The code for the tool is behind a button labelled 'Attach existing track(s) to album'. The code for this tool is as follows:
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "includes/db_connect.pdo.php";
$artistid = $_POST["artistid"];
$albumid = $_POST["albumid"];
echo '<strong>Select each track you would like to add to this album below and type in the track number you want it to have on the album in the box underneith the name of each selected track.</strong><br><br>';
$stmt = $pdo->query("SELECT * FROM track WHERE artist_id = '$artistid'
order by trackname");
while ($row = $stmt->fetch())
{
echo '<form action="includes/attachexistingtracktoalbum.inc.php" method = "post">';
echo '<div class="checkbox">';
echo '<label>';
echo "<input type='checkbox' name='trackid[]' value='".$row['id']."' />";
echo '<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>';
echo ' '.$row['trackname'];
echo '</label>';
echo "<br><label for='albumtracknum'>Track number:</label><br>
<input type='text' name='albumtracknum[]'>
<input type='hidden' name='albumid[]' value='".$albumid,"'>
<br><br>";
echo '</div>';
}
?>
<input type="hidden" name="albumidforreturn" value="<?php echo $albumid;?>">
<button type="submit" name="attachexistingtracktoalbum-submit">Attach track(s) to album</button>
<?php }
else {
header("Location: /index.php");
exit();
}?>
(NB: The post data here is not sanitised for the sql query as it has been passed along in a hidden form from the original album page)
This generates a page with all track names for the current artist available on a list with checkboxes, with each track name being followed by a data entry box to enter the track number for the album being added to.
Submission of the form then hands off to the following include code:
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "db_connect.pdo.php";
$albumid = implode(',',$_POST['albumid']);
$trackid = implode(',',$_POST['trackid']);
$albumtracknum = implode(',',$_POST['albumtracknum']);
$albumidforreturn = $_POST['albumidforreturn'];
// echo 'albumid: '.$albumid.'<br>';
// echo 'trackid: '.$trackid.'<br>';
// echo 'albumtracknum: '.$albumtracknum.'<br>';
$sql = "INSERT INTO trackconnections (albumid, trackid, albumtracknum) VALUES (?,?,?);";
$stmt= $pdo->prepare($sql);
$stmt->execute([$albumid,$trackid,$albumtracknum]);
header("Location: ../albumdetail.php?albumid=$albumidforreturn");
exit();
}
else {
header("Location: ../index.php");
exit();
}
(NB: The commented out echos are there to test what the output is from the previous form)
The 2 problems I am having are that my 'Attach existing tracks to album' form submit:
1. Passes on too much data.
The generated form should only pass on the track ids, album number, and track numbers that have had their checkboxes ticked. For insertion into the 'trackconnections' table.
Instead it narrows down the ticked checkbox track ids only and then creates comma separated values for every available track to select, rather than just those actually selected.
Which leads to annoying outputs such as the following when passing on data from form to include:
albumid: 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4
trackid: 30,14
albumtracknum: ,2,3,,,,,,,,,,,,,,,,,,,,,
Where it should only read as:
albumid: 4,4
trackid: 30,14
albumtracknum: 2,3
Having too much data get passed through means that the row inserts won't be correct on multiple INSERTS once I do get this working, as they won't align with one another in the correct order.
2. The include only INSERTS 1 row to the 'trackconnections' table.
It seems I am misunderstanding how to add multiple rows to the database with my code here.
As having multiple checkboxes ticked on my 'Attach existing tracks to album' form only inserts 1 single row to the database on submission of the form each time.
Consistently the only track that gets added to the 'trackconnections' table is the first track with its checkbox ticked and, because of issue no. 1 above, the albumtracknum is always 0 unless I type a number into the first albumtracknum box on the available checklist.
I need to make tweaks to this code so that both problem 1 and 2 are addressed together, meaning that ticking the checkboxes & adding track numbers into each box following the track names actually adds multiple rows to the database along with their corresponding album track numbers.
I hope someone can help.
EDIT TO SHOW REFINED AND WORKING CODE:
New code for checkbox and textbox sections -
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "includes/db_connect.pdo.php";
$artistid = $_POST["artistid"];
$albumid = $_POST["albumid"];
echo '<strong>Select each track you would like to add to this album below and type in the track number you want it to have on the album in the box underneith the name of each selected track.</strong><br><br>';
$stmt = $pdo->query("SELECT * FROM track WHERE artist_id = '$artistid'
order by trackname");
echo '<form action="includes/attachexistingtracktoalbum.inc.php" method = "post">';
while ($row = $stmt->fetch())
{
echo '<div class="checkbox">';
echo '<label>';
echo "<input type='checkbox' name='trackid[]' value='".$row['id']."' />";
echo '<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>';
echo ' '.$row['trackname'];
echo '</label>';
echo "<br><label for='albumtracknumber'>Track number:</label><br>
<input type='text' name='albumtracknumber_".$row['id']."'>
<input type='hidden' name='albumid[]' value='".$albumid,"'>
<br><br>";
echo '</div>';
}
?>
<input type="hidden" name="albumidforreturn" value="<?php echo $albumid;?>">
<button type="submit" name="attachexistingtracktoalbum-submit">Attach track(s) to album</button>
</form>
<?php }
else {
header("Location: /index.php");
exit();
}
New code for the include INSERT processing -
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "db_connect.pdo.php";
$albumid = implode(',',$_POST['albumid']);
$trackid = implode(',',$_POST['trackid']);
$albumidforreturn = $_POST['albumidforreturn'];
foreach($_POST['trackid'] as $trackidloop) {
$albumtracknum = $_POST["albumtracknumber_{$trackidloop}"];
$sql = "INSERT INTO trackconnections (albumid, trackid, albumtracknum) VALUES (?,?,?);";
$stmt= $pdo->prepare($sql);
$stmt->execute([$albumid,$trackidloop,$albumtracknum]);
}
header("Location: ../albumdetail.php?albumid=$albumidforreturn");
exit();
}
else {
header("Location: ../index.php");
exit();
}
This isn't an entire solution but I see some problems:
You are looping through tracks and creating a new form for each one. The first problem is , you are missing the closing form tag. I guess the browser is automatically creating one, when it sees the next form start tag. ?? That's why you only get one single posted checkbox.
I would put all the track checkboxes into a single form. Then the posted trackid[] array will contain all the checked items.
[EDIT after your comment: The hidden fields albumid[] post the entire array, whereas the trackid[] checkboxes only post the actual checked boxes (HTML spec).
Instead of having albumid[], You could put the trackID and albumID together for the checkbox value, then parse them apart when you handle the post:
$value = $row['id']. ',' . $row['albumid'];
echo "<input type='checkbox' name='trackid[]' value='".$value."' />";
ALSO, the SQL, "INSERT INTO (..) .. VALUES (...) " only inserts one row.
It's easy to do that SQL in a loop for all the checked boxes.
foreach($_POST['trackid'] as $value) {
// parse the $value...
// SQL Insert...
}
EDIT 2: From my own comment:
Like hidden fields, input (text) field arrays also post the entire array (with empty values for blank inputs). (Again, this is not a PHP thing, it's a web browser standard to only post checked checkboxes and radio buttons. But ALL text and hidden INPUTs are posted.) So in your example, you need to code a mechanism to know which textbox goes with each checkbox. Quick and dirty...You could add a row index (0,1,2,3...) as another comma-separated number in your checkbox values, then you'll have the index into the posted textbox array. Alternatively, you could name the textboxes ' .. name="textinput_' . $row['trackid'] . '" ...' (not an array), then upon post, read them in your foreach loop with
$val = $_POST["textinput_{$trackid}"];

Submit values from table not working properly after filtering data

I have a bootstrap table which has a form in it, with each row containing a column where the value can be changed from a drop-down box. On clicking the 'Save changes' button, all the rows will be updated with the new values.
The form/table works as intended in normal cases. But if I use the search functionality of the bootstrap table to filter out a few of the rows and then try to update rows with the values, the wrong rows are getting affected.
So from the example in the above image, if I filter out to view just the second row like in the picture below, then the changes, or the 'Update' query is executed on the actual first row, that is to the row which had 'Bob' as the 'technician'.
I'd like to know how to solve this issue.
Here is the relevant code:
foreach($tickets as $tickets)
{
$users = $app['database']->selectAll('users');
echo ("<input type='text' style = 'display:none' value = '$tickets->id' name = 'ticketid[]'>");
echo "<td class = '$technician->color'>$technician->name</td>";
echo "<td>";
echo '<select name = "user[]" id="user" class="form-control">';
echo "<option value = $technician->id>$technician->name</option>";
foreach($users as $users)
{
echo "<option value = $users->id>$users->name</option>";
}
echo "</select>";
echo "</td>";
echo "</tr>";
}
For the database part, I am calling a function transferTask which accepts first the table name, then two arrays, one array containing updated usernames from the dropdown fields and one containing corresponding ids.
transferTask('tickets', $user[$i], $ticketid[$i])
The above function is executed for each row in the table. I think it's an issue wit the name array being passed from the form to this function but I'm not sure. Help is appreciated!

Why are mySQL query results not displaying text from table when executed in PHP?

The below code is returning rows of checkboxes (the right number per the mySQL table) and with no error. The problem is that it is not grabbing the column values ((as per: ".$row['Zone'].": ".$row['RowNumber']. ))to place beside said checkboxes.
<?php
include'connect.php'
?>
<form method="post" action="chooseDate.php">
<?php
$sql = "
SELECT s.RowNumber, s.Zone,
FROM Seat AS s
LEFT JOIN Booking AS b, ON s.RowNumber = b.RowNumber,
AND b.PerfDate = ?,
AND b.PerfTime = ?,
WHERE b.RowNumber IS NULL,
GROUP BY s.RowNumber
";
$date = "$_POST[Date]";
$time = "$_POST[Time]";
$handle = $conn->prepare($sql);
$handle->execute(array($date, $time));
$res = $handle->fetchAll();
foreach($res as $row) {
echo "<input name='Seat' type='checkbox' value='".$row['Zone'].":
".$row['RowNumber']."'><br>";
}
?>
<input class="mybutton" type="submit" value="Choose Seat"/>
</form>
I have run queries using identical methods and they display the results as expected. The only difference here is that the query is LEFT JOIN. The results display in shell. This is a sample of the results and the expected output of one checkbox.
|**RowNumber**|**Zone**|
|-------------|--------|
|Z20 |box 4 |
Where am I going wrong? Thanks in advance.
Have you looked at the HTML output? You put the text inside the input element. The closing > is after the text.
You could fix that simply by just moving the > to the front, but I think it's bettter to generate a <label> element after the checkbox or surrounding the checkbox. If you give the checkbox an id, and the label a for attribute pointing to that id, the text is clickable too, which make an awesome UX. :)
So I suggest changing the for loop like this:
$idcounter = 0;
foreach($res as $row) {
$id = 'Seat' . ($idcounter++);
echo "<input name='Seat' type='checkbox' id='$id'><label for='$id'>".$row['Zone'].":".$row['RowNumber']."</label><br>";
}
Note that I removed the value attribute. I'm not sure if you would need it, but maybe you need both: the value and the label. If so you can put back that attribute like you had before, as long as you make sure to close the input element before opening the label.

retrieve 1 or more checkbox value from database

this is my html code
<input type='checkbox' name='cbox[]' value='Jaywalking' />
Jaywalking<br>
<input type='checkbox' name='cbox[]' value='Littering' />
Littering<br>
<input type='checkbox' name='cbox[]' value='Illegal Vendor' />
Illegal Vendor
this is my php code
if(isset($_POST['save']))
{
$license_save=$_POST['license'];
$stickerno_save=$_POST['stickerno'];
$fname_save=$_POST['fname'];
$mname_save=$_POST['mname'];
$lname_save=$_POST['lname'];
$no_save=$_POST['no'];
$street_save=$_POST['street'];
$city_save=$_POST['city'];
$bdate_save=$_POST['bdate'];
$violationplace_save=$_POST['violationplace'];
$dd_save=$_POST['dd'];
$mm_save=$_POST['mm'];
$yy_save=$_POST['yy'];
$hh_save=$_POST['hh'];
$min_save=$_POST['min'];
$ampm_save=$_POST['ampm'];
if(is_array($_POST['cbox'])) $violation_save=implode(',',$_POST['cbox']); else $violation_save=$_POST['cbox'];
mysql_query("UPDATE tblcitizen SET license ='$license_save', stickerno ='$stickerno_save', fname ='$fname_save', mname ='$mname_save', lname ='$lname_save', no ='$no_save', street ='$street_save', city ='$city_save', bdate ='$bdate_save', violationplace ='$violationplace_save', dd ='$dd_save', mm ='$mm_save', yy ='$yy_save', hh ='$hh_save', min ='$min_save', ampm ='$ampm_save', violation ='$violation_save', type ='$type_save', officer ='$officer_save', date ='$date_save', ttime ='$ttime_save' WHERE id = '$id'")
or die(mysql_error());
echo "<script>alert('Successfully Edited')</script>";
header("Location: citizen.php");
}
I want to edit some account registered, how can i retrieve 1 or more checkboxes value from the database.
EDITED FOR BETTER ANSWER
if(is_array($_POST['cbox'])) $violation_save=implode(',',$_POST['cbox']); else $violation_save=$_POST['cbox'];
Your query is taking the cbox array, turning it into a string with commas if it is an array (if more than one checkbox was checked), otherwise inserting just one checkbox value with no comma.
To get the values out, just read the string, then compare it with a php strpos()
<?
// Get the checkboxes that were previously selected
$result = mysql_query("SELECT violation FROM tblcitizen WHERE id = '$id'") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
// put the string into a variable
$mystring = $row['violation'];
}
// use a ternary to determine if this checkbox exists
// if so, make the variable $checked to check the checkbox, otherwise leave it blank
$checked = (strpos($mystring, 'Jaywalking')) ? 'checked' : '';
?>
// write the checkbox to the page. and echo the contents of $checked
// if it was found with strpos() then it will be checked, otherwise it will not be
// <?= ?> is a quick way to echo a variable without the echo command
<input type='checkbox' name='cbox[]' value='Jaywalking' <?=$checked;?> />
I don't quite understand your sentence of "how can i retrieve 1 or more check boxes value from the database" but since I can see your update statement, I am assuming that you want to take the one or more value from the check boxes and update the table in the database.
You will receive the check box value in form of an array
You need to loop through the array and get the value
Store value in one variable and you are good to go to store it in the database
foreach ($cbox as $val) {
$Violation .= $val.",";
}
You can always remove the last comma using PHP substring by the way. Cheers, hope this helps you and anybody out there. Thank You.

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