I want to display checked checkbox which are stored as values in a mysql database.
For now the table stores the value of the checkbox being checked in the database. The header and first column are fetched from three different tables in the database. While the values of the checked check-boxes gets saved in a same table.
Here's the code for inserting the data.
$active = "CourseReport";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
require_once './functions/report-functions.php';
$course = Schema::getCourseReport();
$objective = Schema::getObjective();
$goals = Schema::getGoals();
$mainobj = Schema::getMainObjectives();
$subobj = Schema::getSubObjectives();
?>
<form id="addReport" action ='./functions/report-functions.php' method="post">
<table id="table1" class="table table-hover">
<thead>
<?php
echo '<tr><th>Goals</th>';
for ($i = 0; $i < count($course); $i++) {
echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';
}
echo '</tr>';
?>
</thead>
<tbody>
<?php
for ($y = 0; $y < count($goals); $y++) {
echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>
</tr>';
?>
<?php
for( $z = 0; $z < count($mainobj); $z++){
if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>
</tr>';
?>
<?php
for ($j = 0; $j< count($subobj); $j++) {
if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';
for ($x = 0; $x < count($course); $x++) {
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
}
echo '</tr>';
}
}
}
}
}
?>
</tbody>
</table>
<button class="button" name= "submit" value= "Submit">Submit</button>
</form>
report-functions.php
if( isset( $_POST['submit'], $_POST['check'] ) ){
try{
require_once 'db-connect.php';
$conn = DatabaseConnection::getConnection();
$sql= " insert into `Report` (`ColRow`) values (:value) ";
$stmt = $conn->prepare( $sql );
if( $stmt ){
$conn->beginTransaction();
foreach( $_POST['check'] as $index => $value ) {
$result = $stmt->execute( [ ':value' => $value ] );
if( !$result ) {
echo '
<script>
alert("Error, please try submitting again. Error code 1");
window.history.back();
</script>';
}
}
$conn->commit();
echo '<script>
alert("Report was submitted successfully.");
window.location = ".../";
</script>';
}
} catch( Exception $e ){
$conn->rollback();
exit( $e->getMessage() );
}
I expect that once I submit the table, the table should load the same table with the checked checkboxes. I should be able to make the changes and submit the table over and over again.
Please comment if I need to provide any additional information.
When you display your page (in your first section of code), at some point you do this:
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
The value is set to:
value=c"c.$course[$x]->courseId."-o".$subobj[$j]['SubObjId']";
This value is where you get the checked or not value you mentioned in the comments (like c1-o1.1).
Right. So before you do that echo, add a new if condition.
$value = "c$course[$x]->courseId" . "-o$subobj[$j]['SubObjId']";
if (verify_checked($value)) {
$checked_code = "checked=\"checked\"";
}
else {
$checked_code = "";
}
echo "<td><input name='check[]' type=checkbox value=$value id=checked $checked_code ></td>";
The verify_checked(value) function does (from what I understand of your database, you keep the "grid location" of checked elements):
function verify_checked($value)
{
// Connect to the database if needed
// Perform: SELECT count($value) FROM Report
// If the result is >0, return TRUE
// Else return FALSE
}
The idea here is to query the database every time your are about to echo the <input> element.
Note for concatenating text, I find it more legible to put spaces around the . to clearly split what is part of the text and what is the concatenation dot.
As mentioned previously, indentation is critical for understanding of the different contexts. Until I indented your code, I had not realized how the different loops worked in relation to the others.
Related
I'm using HTML, PHP and Ajax to toggle switch in my website. However, only the top most switch is functional. The reason why I use PHP is to display results from my DB, and Ajax is there to toggle switch without reloading the website. Thanks in advance and comment for any questions!
Photo Here :D I have three rows in the DB. Data retrieve fine. Top button works!
ps : removed all classes for simplicity
About main.php and recipe.inc.php. They are separated because recipe.inc.php is used in many documents.
main.php
<?php
$conn = mysqli_connect(localhost,****,****,loginsystem);
//DB connection
$query="SELECT * FROM `recipe` WHERE creator='$uid'";
//SQL Query
$results = mysqli_query($conn,$query);
$array = array();
//Array to save key column of the result in order
while ($row = mysqli_fetch_assoc($results)) {
for ($i = 0; $i < count($row[recipe_ID]); $i++) {
$array[$i] = $row[recipe_ID];
echo '<input type="hidden" id="recipe_ID" name="recipe_ID" value="';
echo $array[$i];
echo '">';
//might confuse you. this is just to hand over recipe_ID to recipe.inc.php
echo '<li>';
echo '<label>';
if($row[status]==1){
echo '<input type="checkbox" id="checkStatus" name="checkStatus" checked="">';
//In case where row[status] is equal to 1. means it's ON
}else{
echo '<input type="checkbox" id="checkStatus" name="checkStatus">';
//OFF otherwise
}
echo '<span class="switcher-indicator"></span>';
echo '</label>';
echo '</li>';
}
}
?>
recipe.inc.php
<?php
if(isset($_POST['checkStatus'])){
$recipe_ID = $_POST['recipe_ID']);
if($_POST['checkStatus']=='ON'){
$status = 1; //to save in DB as boolean. if ON->1
}else if($_POST['checkStatus']=='OFF'){
$status = 0; //if OFF->0
}
$sql = "UPDATE `recipe` SET `status`=$status WHERE creator=$uid AND recipe_ID=$recipe_ID";
//nev
mysqli_query($conn,$sql);
}
?>
and the Ajax part is saved in another js file.
recipe.js
$(document).ready(function() {
$('#checkStatus').on('click', function() {
var checkStatus = this.checked ? 'ON' : 'OFF';
var recipe_ID = $("#recipe_ID").val();
$.post("loginsystem/includes/recipe.inc.php", {
"checkStatus": checkStatus,
"recipe_ID": recipe_ID
},
function(data) {
$('#checkStatus').html(data);
});
});
});
That sounds like all the switches have the same ID. If that is the case, only the first one will work.
Try changing your code to look like this:
<?php
$conn = mysqli_connect(localhost,****,****,loginsystem);
//DB connection
$query="SELECT * FROM `recipe` WHERE creator='$uid'";
//SQL Query
$results = mysqli_query($conn,$query);
$cnt = 1;
$array = array();
//Array to save key column of the result in order
while ($row = mysqli_fetch_assoc($results)) {
for ($i = 0; $i < count($row[recipe_ID]); $i++) {
$array[$i] = $row[recipe_ID];
echo '<input type="hidden" id="recipe_ID-' .$cnt. '" name="recipe_ID" value="'; <============== HERE
echo $array[$i];
echo '">';
//might confuse you. this is just to hand over recipe_ID to recipe.inc.php
echo '<li>';
echo '<label>';
if($row[status]==1){
echo '<input type="checkbox" id="checkStatus-' .$cnt. '" name="checkStatus" checked="">'; //<============== HERE
//In case where row[status] is equal to 1. means it's ON
}else{
echo '<input type="checkbox" id="checkStatus-' .$cnt. '" name="checkStatus">'; //<================ HERE
//OFF otherwise
}
echo '<span class="switcher-indicator"></span>';
echo '</label>';
echo '</li>';
}
$cnt++; <=========== HERE
}
?>
I apologize in advanced because I believe that my question may be kind of confusing.
I have three different PHP files. The first one asks you how many different products you want (1-20) in which the variable is called $quantity. Once a number is selected from a drop down box, you are taken to the next PHP page that automatically generates a table with $quantity number of rows and in each row there is a dropdown box that is being populated from a database. There is also another column with empty textboxes for the quantity.
Here is the code for that:
<?php
$quantity = "";
$i = 1;
if (isset($_POST['quantity'])) {
$quantity= $_POST['quantity'];
$var = "";
while($row = mysqli_fetch_array($result1)){
$var = $var . "<option>" . $row['product_name'] . "</option>";
}
echo "<left><table border='1' width='1%'><tr><td><center>Product</td><td>Quantity</center></td></tr>";
while ($i <= $quantity){
echo "<tr><td><select name='product[]' size='1'>";
echo $var;
echo "</select></td><td><input name='quant[]' size='5' /></td></tr>";
$i++;
}
echo "</table></left>";
}
?>
Once each product and its desired quantity is entered, the user clicks submit and they are taken to the final PHP page. This PHP page is supposed to be a confirmation page with all of the customer information and their selected products and quantities. HOWEVER, my code is only printing out the LAST product and quantity in the table from the second PHP page. For example if the table is:
Product Quantity
Bed 1
Chair 2
Couch 3
My confirmation page prints out a one row table with ONLY the information for Couch instead of multiple rows with ALL three of those products. Here is my code for the last PHP page:
<body>
<?php
$curTime= "";
$customerbox= "";
$region= "";
$products = $_POST['product']; //I changed this (edit 2)
$quants = $_POST['quant']; //I changed this (edit 2)
if (isset($_POST['curTime'])) $curTime= $_POST['curTime'];
if (isset($_POST['customerbox']))$customerbox= $_POST['customerbox'];
if (isset($_POST['region']))$region= $_POST['region'];
if (isset($_POST['product']))$product= $_POST['product'];
if (isset($_POST['quant']))$quant= $_POST['quant'];
$error= false;
$done=false;
if ((isset($curTime) && empty($curTime))) {
print "Please enter the date.<br/>";
$error = true;
}
if (!isset($_POST['customerbox'])) {
print "Please select your customer.<br/>";
$error = true;
}
if (!isset($_POST['region'])){
print "Please select your region.<br/>";
$error = true;
}
if (!isset($_POST['product'])){
print "Please select your product.<br/>";
$error = true;
}
if ((isset($quant) && empty($quant))){
print "Please enter the quantity.<br/>";
$error = true;
}
else{
$error = true;
$done = true;
}
for ($i =0; $i < count($products); $i++){
echo $products[$i]; //I changed this
echo $quants[$i]; //I changed this
}
?>
<br>
<table style= border-collapse:collapse width="1%"border="2" align="center" <?php if (!$done){ echo "hidden";}?>
<tr>
<th>Date</th>
<th>Customer</th>
<th>Region</th>
<th>Product</th>
<th>Quantity</th>
</tr>
<tr>
<td><center><?php print $curTime?></td></center>
<td><center><?php print $customerbox?></td></center>
<td><center><?php print $region?></td></center>
<td><center><?php print $product?></td></center>
<td><center><?php print $quant?></td><center>
</tr>
</table>
</body>
I believe this problem is occurring because when I am creating the table with $quantity rows, it's continuously naming each dropdown box $product so it's taking the very last value as $product and printing that.
Is there anyway to print out all of the products with their respective quantities?
Thank you in advance!
For your product and quant dropdown boxes you should use name="product[]" and name="quant[]".
This will send an array instead of one value as $_POST variable, and you can then loop over this array by using
$products = $_POST[product];
$quants = $_POST[quant];
for ($i =0; $i < count($products); $i++){
echo $products[$i]; //echo one product
echo $quants[$i]; //echo one quantity
//etc..
}
I help develop my school's website what I can not figure out is why on a certain page the sidebar and footer go into the table main. It only does this for two thing custodial and kitchen even when I think the code for say administrators is the same code and looks the same to me.
This is the code used to generate the teachers page
The link below will take you to the broken page since I can't post pictures
http://gwhs.kana.k12.wv.us/academics/display.php?action=teacher&id=103
While the link below will take you to one that actually works
http://gwhs.kana.k12.wv.us/academics/display.php?action=teacher&id=24
If you want the entire file for this code let me know and I will post a link
function dTeacher() {
global $db, $id;
if ($stmt = $db->prepare("SELECT name, department, schedule, education, whyteach, phone, email, image, quote FROM teachers WHERE id = ?"))
{
$stmt->bind_param('i', $id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
$stmt->close();
$schedule = array();
$schedule = explode(",",$row['schedule']);
$education = explode(",",$row['education']);
$noshow = array(20, 14, 25, 15, 24, 21, 23);
print '<h1>Viewing '.$row['name'].'\'s Profile!</h1>';
if ($row['image']) {
print '<img style="max-width:40%; display: block; margin: 2% auto;" src="'.$row['image'].'" alt="Teacher Image Here">';
}
if (!(in_array($row['department'], $noshow))) {
print '<h3>Schedule</h3>
<table id="maindata">
<tr id="head"><td style="width:30%;">Period</td><td style="width:70%;">Class</td></tr>';
for ($i=0; $i<count($schedule); $i++)
{
$oddeven = ($i%2==0) ? "even" : "odd";
$scnum = $schedule[$i];
$scresult = $db->query("SELECT id, name FROM classes where id = {$scnum} LIMIT 1");
$scrow = $scresult->fetch_assoc();
if ($scnum == 1337) {
$scrow['name'] = "OFF";
} //off periods
print '<tr id="'.$oddeven.'"><td style="width:30%;">'.$i.'</td><td style="width:70%;">'.$scrow['name'].'</td></tr>';
}
}
if ($row['education']) {
print "</table><h3>Education</h3>";
for ($i=0; $i<count($education); $i++)
{
$oddeven = ($i%2==0) ? "even" : "odd";
print '<table id="maindata"><tr id="'.$oddeven.'"><td>'.$education[$i].'</td></tr>';
}
print '</table>';
}
if ($row['phone'] || $row['email']) {
print '
<h3>Contact</h3>
<table id="maindata"><tr id="even"><td style="width:30%;">Phone</td><td>'.$row['phone'].'</td></tr>
<tr id="odd"><td style="width:30%;">Email</td><td>'.$row['email'].'</td></tr></table>';
}
if ($row['whyteach'] != "") {
print '<h3>Why do you teach?</h3>
<table id="maindata"><tr id="even"><td><p>'.$row['whyteach'].'</p></td></tr></table>';
}
if ($row['quote'] != "") {
print '<h3>Favorite Quote</h3>
<table id="maindata"><tr id="even"><td><p>'.$row['quote'].'</p></td></tr></table>';
}
}
else {
print "Error with your request.";
die();
}
}
You have a bug here, you are not closing table tag:
if (!(in_array($row['department'], $noshow))) {
print '<h3>Schedule</h3>
<table id="maindata">
<tr id="head"><td style="width:30%;">Period</td><td style="width:70%;">Class</td></tr>';
for ($i=0; $i<count($schedule); $i++)
{
$oddeven = ($i%2==0) ? "even" : "odd";
$scnum = $schedule[$i];
$scresult = $db->query("SELECT id, name FROM classes where id = {$scnum} LIMIT 1");
$scrow = $scresult->fetch_assoc();
if ($scnum == 1337) {
$scrow['name'] = "OFF";
} //off periods
print '<tr id="'.$oddeven.'"><td style="width:30%;">'.$i.'</td><td style="width:70%;">'.$scrow['name'].'</td></tr>';
}
echo "</table>";
}
Because of this, when the profile has Schedule the table is not closed and the page will display bad.
And closes it here:
if ($row['education']) {
print "<h3>Education</h3>";
With two modifications the web should do its work fine.
Take a look this HTML validator, it will help you:
http://validator.w3.org/check?uri=http%3A%2F%2Fgwhs.kana.k12.wv.us%2Facademics%2Fdisplay.php%3Faction%3Dteacher%26id%3D103&charset=%28detect+automatically%29&doctype=Inline&group=0
Best regards.
First words: You should re-think the layout. Creating multiple tables to display page content is not the best approach and furthermore IDs have to be unique. So for valid HTML you can't have multiple tables with the ID maindata.
As mentioned by cmorrissey in the comments, you're not closing the first table, unless you enter the next if statement. Furthermore this part
if ($row['education']) {
print "</table><h3>Education</h3>";
for ($i=0; $i<count($education); $i++) {
$oddeven = ($i%2==0) ? "even" : "odd";
print '<table id="maindata"><tr id="'.$oddeven.'"><td>'.$education[$i].'</td></tr>';
}
print '</table>';
}
of your code closes the previous <table id="maindata"> but opens a new one in each iteration of the loop. After the loop, your closing just one of them. So if it is correct, that you want to create multiple of these tables, you should close them in the loop as well:
for ($i=0; $i<count($education); $i++) {
$oddeven = ($i%2==0) ? "even" : "odd";
print '<table id="maindata"><tr id="'.$oddeven.'"><td>'.$education[$i].'</td></tr>';
print '</table>';
}
I have this php statement that collects data from a database table. It loops over all rows and separates them into tables of 2 (home team and away team for that game). I also have radio buttons so the user can pick which team they would like to win for each game. There are 9 games.
$games = array();
for($num = 1; $num <= 9; $num++)
{
$games[$num] = "<table border='1'><tr><b><h4>Game ".$num."</h4></b><th>Home</th><th>Draw</th><th>Away</th></tr>";
}
while ($row = mysql_fetch_array($rs))
{
for($num = 1; $num <= 9; $num++)
{
$games[$num] .=
" <tr>
<td><input type='radio' id='home".$num."' name='game".$num."' value='".$row['home'.$num]."' > ".$row['home'.$num]."</td>
<td>Draw <br /><input type='radio' id='draw".$num."' name='game".$num."' value='0'></td>
<td>".$row['away'.$num]."<input type='radio' id='away".$num."' name='game".$num."' value='".$row['away'.$num]."'></td>
</tr>";
}
}
On submit, i want to be able to do something for each game via SELFSUBMIT.
So if a user selects home team for game n, i want to display a message.
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if($_POST['game".$num."'] = ('home'.$num))
{
echo ('home'.$num);
}
}
Thats my wrong php code. Please tell me if i can workaround this.
You might want to use jquery
$(document).ready( function(){
$("input[id^=home]").on("click", function(){
$("#spanDisplay").html( $(this).attr("id") );
//you can also display $(this).attr("name") or $(this).val() to print the value
});
});
In your html, you can use span or div to display the value of id for example.
So in your span
<span id="spanDisplay"></span>
UPDATE: using PHP only
$games[$num] .= "<form name="aForm" method="POST" action="afterSubmit.php">";
for($num = 1; $num <= 9; $num++){
$games[$num] .= "<tr><td><input type='radio' id='home".$num."' name='game".$num."' value='".$row['home'.$num]."'> ".$row['home'.$num]."</td>
<td>Draw <br /><input type='radio' id='draw".$num."' name='game".$num."' value='0'></td>
<td>".$row['away'.$num]."<input type='radio' id='away".$num."' name='game".$num."' value='".$row['away'.$num]."'></td></tr>";
}
$games[$num] .= "</form>";
You will need to surround your input with the form tag, submit and post it to the next page for instance afterSubmit.php. So in afterSubmit.php page, you can put something like this:
for($num = 1; $num <= 9; $num++){
if( isset( $_POST['game".$num."'] ) ){
echo $_POST['game".$num."']; //echo the value
}
}
I am trying to work my head round this, I am using the following code to check the answers to a quiz and output either CORRECT or INCORRECT depending on the result of the comparison, and if the answer field is black (which only comes from the feedback form) a different message is displayed.
I cant quite work out how to apply the php count function in this situation though, what im trying to get it to do it count the amount of CORRECT and INCORRECT answers and add the two together, and then I can work out a % score from that.
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT * FROM itsnb_chronoforms_data_answerquiz a, itsnb_chronoforms_data_createquestions
q WHERE a.quizID='$quizID' AND a.userID='$userID' and q.quizID=a.quizID and
a.questionID = q.questionID ORDER BY a.cf_id ASC" or die("MySQL ERROR: ".mysql_error());
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}}
?>
Iv found this example and have been trying to work out how to work it in, but cant think how to count the results of an if statement with it ?.
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
$result = count($people);
echo $result;
?>
Just increment two counters
$correct_answers = 0;
$incorrect_answers = 0;
while ($row = mysql_fetch_array($result)) {
if ($row['correctanswer'] == '') {...
} elseif ($row['correctanswer'] == $row['quizselectanswer']) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$correct_answers++;
} else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$incorrect_answers++;
}
}
Simply increase some counter in each branch of your if/elseif/else construct...
$counters = array( 'blank'=>0, 'correct'=>0, 'incorrect'=>0 );
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ( ''==$row['correctanswer'] ) {
echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';
$counters['blank'] += 1;
}
elseif ( $row['correctanswer']==$row['quizselectanswer'] ) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$counters['correct'] += 1;
}
else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$counters['incorrect'] += 1;
}
}
echo '#correct answers: ', $counters['correct'];
How about creating a variable with a count of correct answers? For each question you loop through, increment the value by one.
<?php
$correct_answers = 0;
while($questions) {
if($answer_is_correct) {
// Increment the number of correct answers.
$correct_answers++;
// Display the message you need to and continue to next question.
}
else {
// Don't increment the number of correct answers, display the message
// you need to and continue to the next question.
}
}
echo 'You got ' . $correct_answers . ' question(s) right!';
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT ... ";
$result = mysql_query($query) or die(mysql_error());
$countCorrect = 0;
$countIncorrect = 0;
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
$countCorrect++;
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {
$countIncorrect++;
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}
}
echo ((int)($countCorrect/($countIncorrect + $countCorrect) * 100)) . "% answers were correct!" ;
?>