How to count the unchecked checkboxes in a while loop - php

$query = mysql_query("SELECT DISTINCT status, vendor FROM tbl_softwareinstalled WHERE vendor NOT LIKE ''");
$nums = mysql_num_rows($query);
echo "<form name = 'filter' action='softwarefilter.php' method='POST'>
$nums<br>
<table border = 1><tr><td> </td>
<td><strong>Software Vendor</strong></td></tr>";
$ctr1 = 1;
while($fetch = mysql_fetch_array($query)) {
$vendor = $fetch['vendor'];
$status = $fetch['status'];
if(($ctr1 % 2)==1)
{ print "<tr bgcolor = 'white'>";}
else
{ print "<tr bgcolor = '#EEEEEE'>"; }
print "<td><input name= 'chk[]' type='hidden' value='0'>
<input type = 'checkbox' name = 'chk[]' value = '$vendor' ";
if ($status == 'Enabled') {
print "checked = 'checked'></td><td>$vendor</td></tr>"; }
else {
print "></td><td>$vendor</td></tr>"; }
$ctr1++;
}
print "</table>";
print "<input type = 'submit' name = 'submit' value = 'Update Filter'>
</form> ";
$submit = $_POST['submit'];
if(isset($submit))
{
$chk = $_POST['chk'];
$count = count($chk);
if (empty($chk)) {
echo "qweqwe<br>";
}
for ($i=0; $i<$count; $i++) {
$abc = $chk[$i];
$query = mysql_query("UPDATE tbl_softwareinstalled SET status = 'Enabled' WHERE vendor = '$abc'");
}
echo '<meta http-equiv="refresh" content="0.5;url=/assets/softwarefilter.php">
<script language="javascript">
alert("Software filter updated.");
</script>';
}
Hi, how can I count the UNCHECKED CHECKBOXES in a while loop with this block of code?
Let's say for example I have 10 checkboxes with 10 values, the user checked 3 checkboxes (with values: 'abc', 'def', 'ghi'), after submitting it. It will count all the UNCHECKED checkboxes and echoes the value of it. The values of 3 checked checkboxes SHOULD NOT be echoed.

The browser will only tell you which have been checked. Pull all the possible boxes from your database, and then remove those that the browser has told you are checked.

I had worked on a similar thing for counting unchecked boxes.
place two input fields of input type checkbox and input type hidden with different names
<input type="hidden" class="" name="test[]" value="0">
<input type="checkbox" class="" name="checkbox[]" value="1">
then on submit
if (isset($_POST['submit'])) {
$cnt = array();
$counter =0;
$testcnt = 0;
$cnt = 0;
if (isset($_POST['test'])) {
$testcnt = count($_POST['test']);
}
if (isset($_POST['checkbox'])) {
$cnt = count($_POST['checkbox']);
}
echo 'the count of unchecked boxes is ';
print_r($testcnt-$cnt);
}
For your case change this to:
<input name= 'unchecked[]' type='hidden' value='0'>
then on submit when your checking for isset(submit) you can add the following an d change accordingly
$unchecked_input = count($_POST['unchecked']);
$chk = $_POST['chk'];
$count = count($chk);
echo $unchecked_input-$count; //will output the count of unchecked boxes

Related

Duplicate checkbox remove in php

I have two tables named bookings and packages. Checked checkboxes are retrieved from bookings table and are working perfectly. But I also need unchecked check boxes from packages table. The problem is checked checkbox values display again.
<?php
$get_pro = "select * from booking";
$result = mysqli_query($con, $get_pro);
$book_packages = $row_pro['Book_Packages'];
$book_packages = substr(trim($book_packages) , 0, -1);
$split_pkg = (explode(",", $book_packages));
if (!empty($split_pkg)) {
foreach ($split_pkg as $book_pkg) {
$checked = (in_array($book_pkg, $split_pkg)) ? 'checked="checked"' : '';
?>
<input type="checkbox" name="pkg_list_name[]" value="<?php echo $book_pkg; ?>" size="17" <?php echo $checked; ?>> <?php echo $book_pkg; ?> <br>
<?php
}
}
$get_pros = "select * from package";
$results = mysqli_query($con, $get_pros);
while ($row_pros = mysqli_fetch_array($results)) {
$package_name = $row_pros['Pkg_Name'];
if ($package_name != $split_pkg) {
echo "<input type='checkbox' data-parsley-required='true' value='$package_name' data-parsley-trigger='click' id='checkbox1' name='pkg_list_name[]'>
<label>$package_name</label><br> ";
} else {
}
}
?>
You shouldn't have two loops. You should only create the checkboxes from the package table. When you're creating those checkboxes, add checked="checked" if the package name is in $split_pkg.
$book_packages = trim($row_pro['Book_Packages']);
$split_pkg = array_map('trim', explode(',', $book_packages));
$get_pros = "select * from package";
$results = mysqli_query($con, $get_pros);
while ($row_pros = mysqli_fetch_array($results)) {
$package_name = $row_pros['Pkg_Name'];
$checked = (in_array($package_name, $split_pkg)) ? 'checked="checked"' : '';
echo "<label><input type='checkbox' data-parsley-required='true' value='$package_name' data-parsley-trigger='click' name='pkg_list_name[]' $checked>
$package_name</label><br> ";
}
BTW, it's not a good idea to to put comma-separated values in database columns. You should have a separate row for each booking. Then you would be able to join the two tables easily.

How to insert multiple rows by select or checkbox

I've got a problem with inserting multiple row to one table.
I've got a 3 tables:
1. student with id_student
2. ankieta with id_ankieta
3. student_ankieta with id_student and id_ankieta
I want to choose students from database using select or checkbox and choose one id_ankieta. After confirming, there are rows created in table (student_ankieta).
Now I can choose students but when I confirm, only one student gets added to the database.
Can anyone help me corect the code?
<?php
echo'<form method="post" action="student_ankieta.php">
<div class="box" style="margin:0 auto; top:0px;">
<h1>Student - ankieta:</h1>
<label>
<span><br/>Ankieta:</span>
</label>
<select class="wpis" name="id_ankieta">
<option>wybierz ankiete</option>';
$query = "SELECT * FROM ankieta";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id_ankieta'].'">' . $row{'rok_akademicki'}.' '. $row{'semestr_akademicki'}.' '.$row{'active_ankieta'} .'</option>';
}
echo '
</select>';
$query = "SELECT * FROM student";
$result = mysql_query($query);
echo'
<label>
<span><br/>Wybierz stundentów:</span>
</label>
<select multiple="multiple" name="id_student[]" size="10">';
while ($row = mysql_fetch_assoc($result))
{
echo '<option class="wpis" value="'.$row['id_student'].'" />'.$row{'pesel'}.' '. $row{'nazwisko'}.' '.$row{'imie'} .'</option>';
}
echo'<br/><input class="button" type="submit" value="Dodaj ankiete" name="dodaja">';
if(isset($_POST['dodaja']))
{
$id_ankieta = $_POST['id_ankieta'];
if(empty($_POST['id_ankieta']))
{
echo '<p style="margin-top:10px; font-size:75%; font-family: Calibri; color: red; text-align:center;">Musisz wypełnić wszystkie pola.</p>';
}
else
{
$id_student = $_POST['id_student'];
for ($i = 0; $i < count($id_student); $i++)
{
$id_student = $id_student[$i];
mysql_query("INSERT INTO student_ankieta (id_student, id_ankieta) VALUES ('" . $id_student . "','$id_ankieta')");
}
}
}
echo'</div></form>';?>
Put all students in to an array with the key = id_student
$query = "SELECT * FROM ankieta";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
students[$row['id_student']] = array($row['pesel'],$row['nazwisko'],$row['imie'];
}
If the form was posted the confirm will = 1 (from hidden input)
When first enter script "confirm will = 0
When zero, display all student with a check box with a name which includes the id_student in the format of n-i_student.
if intval($_POST['confirm']) = 0){
echo '<form action = "confirm.php" method="post"><input type="hidden" name="confirm" value="1"/><table>';
foreach ($students as $id => val){
echo "<tr><td><input type=\"checkbox\" name=\"n-$id\" value=\"1\" /> Select </div></td>$val[0]<td>$val[0]</td><td>$val[1]</td><td>$val[2]</td></tr>";
}
echo '</table></form>';
}
When confirm = 1
The checkboxes that were checked are inserted.
Check each post value for a key the starts with "n-"
get the rest of the key value after the n- for the id_student value.
Still 1 Major Problem, I do not know where to get the $id_ankieta'
And match it with the id_student.
I left that value as $val[???]
elseif intval($_POST['confirm']) = 1){
foreach ($_POST as $k =>$val){
if (inval($val) == 1 && substr($k,0,2) == 'n-'){
$id = substr($k,2);
$sql = mysql_query("INSERT INTO student_ankieta (id_student, id_ankieta) VALUES ('$id','" . $students[$id][$val[???]] . "')");
}
}
}

Submit button needs to be clicked twice to get my results from radio buttons in a php script

The problem with this code is that I can't read the results in $survey_Answers1 except after clicking on the submit button twice.
file:survey.php
<?PHP
session_start();
//=========================================================
//The following page is used to create a dynamic survey.
//=========================================================
$qNum = 'q1';
$question = 'Question not set';
$answerA = 'unchecked';
$answerB = 'unchecked';
$answerC = 'unchecked';
$qID = array();
$question = array();
$A = array();
$B = array();
$C = array();
$survey_Answers = array();
$survey_Answers1 = '';
//============================================
// OPEN A CONNECTION TO THE DATABASE
//============================================
$user_name = "root";
$password = "";
$database = "surveyTest";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$SQL = "SELECT * FROM tblquestions";
if ($db_found) {
$result = mysql_query($SQL);
$numRows = mysql_num_rows($result); //return number of rows in the table
echo '<FORM NAME ="form1" METHOD ="POST" ACTION ="survey.php">';
for ($i = 1; $i <= 2; $i++)
{
$db_field = mysql_fetch_assoc($result);
$qID[$i] = $db_field['QID'];
$question[$i] = $db_field['Question'];
$A[$i] = $db_field['qA'];
$B[$i] = $db_field['qB'];
$C[$i] = $db_field['qC'];
echo '<P>';
print $question[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'A'>";
print $A[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'B'>";
print $B[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'C'>";
print $C[$i];
if (isset($_POST[$qNum])){
$survey_Answers1 = $survey_Answers1.', '.$_POST["$qNum"];
}
//var_dump($survey_Answers1);
$question_Number = ltrim($qNum,'q');
$question_Number++;
$qNum ='q'.$question_Number;
}
echo '<p>';
//$_SESSION['answers'] = $survey_Answers1;
//var_dump($_SESSION['answers']);
echo "<INPUT TYPE = 'hidden' Name = 'h2' VALUE = '".$survey_Answers1."'>";
echo '<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Click here to vote">';
var_dump($_POST['h2']);
echo '</form>';
mysql_close($db_handle);
}
else {
print "Error getting Survey";
mysql_close($db_handle);
}
?>
The value stored in var_dump($_POST['h2']); after hitting clicking the submit button once is: string '' (length=0)
P.S., using session variables doesn't resolve the problem, so please don't suggest this answer!!!!
Try to insert after for-loop
for ($i = 1; $i <= 2; $i++)
{
// your code here
}
if (empty($_POST['h2'])) $_POST['h2'] = $survey_Answers1; // insert this line
Or use JavaScript, insert to the end of file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
if ($('form').length > 0) {
$('form').submit(function(e){
var answers = '';
$('input[type=Radio]:checked').each(function() {
if (answers !== '') {
answers += ',';
}
answers += $(this).val();
})
$('input[name=h2]').val(answers);
});
}
})
</script>
From what I see your problem is with your for loop try to see whats returning survey_Answers1 in each loop. you can try this to see whats returning each time it loops and part from there
if (isset($_POST[$qNum])){
$survey_Answers1 = $survey_Answers1.', '.$_POST["$qNum"];
?>
<script type="text/javascript"><?php echo $survey_Answers1; ?></script>
<?php
}

Passing an array in PHP to another PHP script through html hidden form element

My question is that when I copy my array elements between different php scripts using session variables, nothing gets printed out. The following are my two php files.
file1.php
$SQL = "SELECT * FROM tblquestions";
if ($db_found) {
$result = mysql_query($SQL);
$numRows = mysql_num_rows($result); //return number of rows in the table
echo '<FORM NAME ="form1" METHOD ="POST" ACTION ="file2.php">';
for ($i = 1; $i <= 2; $i++)
{
$db_field = mysql_fetch_assoc($result);
$qID[$i] = $db_field['QID'];
$question[$i] = $db_field['Question'];
$A[$i] = $db_field['qA'];
$B[$i] = $db_field['qB'];
$C[$i] = $db_field['qC'];
echo '<P>';
print $question[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'A'>";
print $A[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'B'>";
print $B[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'C'>";
print $C[$i];
//if (isset($_POST[$name_Value]))
$survey_Answers[$i-1] = $_POST[$qNum];
print '</BR>'.$survey_Answers[$i-1]."</BR>";
$question_Number = ltrim($qNum,'q');
$question_Number++;
$qNum ='q'.$question_Number;
}
echo '<p>';
session_start();
$_SESSION['answers'] = $survey_Answers;
echo '<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Click here to vote">';
echo '</form>';
On my Second file (file2.php), I have the following:
<?PHP
session_start();
if (isset($_POST['Submit1'])) {
$results = $_SESSION['answers'];
print $results[0];
?>
Nothing gets printed out when executing the above code.
Thanks in advance
I am pretty sure that the session values stored need to be strings.
In file1.php change:
$_SESSION['answers'] = $survey_Answers;
to this:
$_SESSION['answers'] = json_encode($survey_Answers);
Then in file2.php change:
$results = $_SESSION['answers'];
to this:
$results = json_decode($_SESSION['answers']);

Help with retrieving answers from radio buttons

$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'pmdb';
mysql_connect($host,$user,$pw);
mysql_select_db($db);
$result = mysql_query("SELECT * FROM Questions WHERE QuizID=1");
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
$array[] = $row;
}
for($i=0; $i<=($num_rows-1); $i++)
{
$title = $array[$i]['Title'];
$ans1 = $array[$i]['Answer1'];
$ans2 = $array[$i]['Answer2'];
$ans3 = $array[$i]['Answer3'];
$ans4 = $array[$i]['Answer4'];
echo $title.'<br>';
echo '<form method="post">';
echo '<input type="radio" name="ans'.$i.'">'.$ans1.'<br>';
echo '<input type="radio" name="ans'.$i.'">'.$ans2.'<br>';
echo '<input type="radio" name="ans'.$i.'">'.$ans3.'<br>';
echo '<input type="radio" name="ans'.$i.'">'.$ans4.'<br>';
}
echo '<input type="submit" value="submit" id="submit">';
echo '</form>';
I manage to display the question followed by the corresponding choices and at the bottom a submit button.
How would I, on click of the submit button, get the values that the user have chosen for each question that was looped out from the database? ans1, ans2, etc.
This is necessary to compare their answer to the answer key and compute their score.
.help please! Thank you very much and More power!
Assign a value to each of the radio inputs, the updated script could be:
$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'pmdb';
mysql_connect($host,$user,$pw);
mysql_select_db($db);
$result = mysql_query("SELECT * FROM Questions WHERE QuizID=1");
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
$array[] = $row;
}
//Start the form
echo "<form method=\"post\" action=\"path/to/receiving.php\">\n";
for($i=0; $i<=($num_rows-1); $i++)
{
//Render a question + the answer choices
echo $array[$i]['Title']."<br />\n";
for ($j=1;$j<=4;$j++) {
echo "<input type=\"radio\" name=\"ans$i\" value=\"$j\">".
$array[$i]['Answer'.$j]."<br />\n";
}
}
//End the form
echo "<input type=\"submit\" value=\"submit\" id=\"submit\">\n</form>";
Now to read the values of the answers from within PHP:
echo $_POST["ans1"];
//The answer given for question 1, will be between
// 1-4 or null (if they didn't answer

Categories