I have a system where I rearrange navigational items.
It stores the new order in an array and then I use a for loop to go through the array and update the database.
<?php
$apageid = array();
$apagename = array();
$apageorder = array();
$q = "SELECT g.id, g.title, n.order FROM tbl_general g INNER JOIN tbl_navigation n ON n.pageid = g.id WHERE n.type = '$_SESSION[parent]' ORDER BY n.order";
$return = $database->query($q);
while($row=mysql_fetch_assoc($return)){
$apageid[] = $row['id'];
$apagename[] = $row['title'];
$apageorder[] = $row['order'];
}
$count = count($apageid);
$bpageid = array();
$bpageorder = array();
?>
<div class="form-holder">
<?php
//run through each page one at a time and update the order of the menu
mysql_data_seek( $return, 0 ); //reset the pointer to do the same query
$i = 0; //the count for saving the new configuration
while($row=mysql_fetch_assoc($return)){
$id = $row['id'];
$title = $row['title'];
$order = $row['order'];
?>
<div class="form-row">
<div class="form-label">
Page Name
</div>
<div class="form-field">
<select class="select-small" name="<?php echo $bpageid[$i]; ?>">
<?php
for($j=0; $j<$count; $j++){
if($apageid[$j] == $id) {
$selected = true;
} else {
$selected = false;
}
?>
<option value="<?php echo $apageid[$j]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apagename[$j]; ?></option>
<?php
}
?>
</select>
<select class="select-small" name="<?php echo $bpageorder[$i]; ?>">
<?php
for($k=0; $k<$count; $k++){
if($apageorder[$k] == $order) {
$selected = true;
} else {
$selected = false;
}
?>
<option value="<?php echo $apageorder[$k]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apageorder[$k]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<?php
$i++;
}
?>
This first chunk of code is the menu where you can reorder items.
Initially it loads up the current select and allows you to change the ordering.
function reorderChildren($pageid, $pageorder){
global $database;
$count = count($pageid);
//run through each page one at a time and update the order of the menu
for($i=0; $i<$count; $i++){
//set a few variables
$pid = $pageid[$i];
$porder = $pageorder[$i];
echo "pid = $pid porder = $porder";
$q = "UPDATE tbl_navigation SET order = '$porder' WHERE pageid = '$pid' AND type = '$_SESSION[parent]'";
$database->query($q);
}
return 0;
}
The information then ends up being passed here and the problem appears to be the for loop is never executed.
Can anyone see why this would be?
It's not the naming used, I've checked them.
Am I storing information in the arrays correctly?
Can I make it clear that it's $bpageid and $bpageorder that are the arrays carrying the information forward.
Thanks!
Was a simple fix!
The problem was that the select name needed to be just name="bpageid[]" rather than what I listed above. Silly!
You have just initilized $bpageid = array(); at top after first while loop.No value is assigned
after that you using
<select class="select-small" name="<?php echo $bpageid[$i]; ?>">
but no value is in $bpageid[$i] so name of this select box is blank.
It might be problem. check this and do as required.
you could try to construct a json from the options of the select element store it to a hidden field or send ajax request to php script for processing , order could be made from a "weight" value 1,2,3 etc.... sort it with php and loop to display
Related
i am creating a quiz website using php where there are 4 questions for users to answer. there is a home page before this for them to choose either math or lit that they wish to do.
after selecting the subject, user need to answer the question and submit their answer, then the php code will calculate their score and count the number of correct/wrong answers.
<ArrayquesAns.php> is the array of questions and answers
it looks something like this, there are 2 array in this php, 1 is math question and another 1 is lit question
and here is the main code where it will generate questions from the question pool randomly. i also tried to put in the code to calculate score
<html>
<body>
<?php
require_once 'ArrayQuesAns.php'; //retrieve array of ques
$_SESSION["subject"] = $_GET['subject']; //suppose to put value when session starts
$_SESSION["name"] = $_GET['name'];
$subject = $_SESSION["subject"];
$name = $_SESSION["name"];
$url = "displayScore.php?name=" . $name . "&subject=" . $subject . "&";
if ($subject == "mathematics") { //math session
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
$MathquesRand = array(); //New array to contain the 4 random rows
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?> </h1>
<p>Hello <?= $name ?>! You may start your quiz !<p>
<hr>
<?php foreach ($MathquesRand as $qtsno => $value) { ?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
} else { //Lit Section
$LitQues_key = array_rand($Litques, 4);
$LitquesRand = array();
$i = 0;
foreach ($LitQues_key as $key) {
$LitquesRand[$i] = $Litques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?></h1>
<p>Hello <?= $name ?> ! You may start your quiz !<p>
<hr>
<?php foreach ($LitquesRand as $qtsno => $value) {
echo $value["ques"], " = \t";
?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
}
?>
<!--Exit-->
<button type="button">EXIT</button>
</body>
</html>
i think this part is where it has issue
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
the code should match user input answer with array question/answer to see if the answer is correct. every correct question will *5 and every wrong answer will *3 (the formula is in the code).
i am not sure if i place the code in the wrong bracket hence its not working or there is some logic error or should i run the code to find the score in a separate php?
after user submit their answer, it will redirect to another page that display their score and number of correct/wrong answers like this
score display html
Based on your original version of the MC test, please find below a working version:
To make it simple, I have removed the "Name" and "Subject" of the form to demonstrate the necessary coding.
You can still use the array_rand to draw 4 random questions
However, after the questions are displayed to the student (and student can input the answer) and clicked "Submit Attempt", the page will remember the random questions drawn - I have used a trick :- to store the questions randomly drawn into a hidden input box
The system will compare the student's submitted answer with that of the correct answer and determine whether it is correct or wrong, and show the score
To fix the "undefined array" errors you encountered, I applied the isset function on places relating to the $_GET variables. (Actually these are warnings, not errors, but it is for sure a good practice to use isset)
<?php
//require_once 'ArrayQuesAns.php'; //retrieve array of ques
$Mathques=array(
1=> array('no'=>1, 'ques'=>"3+1", 'ans'=>"4"),
2=> array('no'=>2, 'ques'=>"3+3", 'ans'=>"6"),
3=> array('no'=>3, 'ques'=>"3+4", 'ans'=>"7"),
4=> array('no'=>4, 'ques'=>"3+5", 'ans'=>"8"),
5=> array('no'=>5, 'ques'=>"3+6", 'ans'=>"9"),
6=> array('no'=>6, 'ques'=>"3+7", 'ans'=>"10"),
7=> array('no'=>7, 'ques'=>"3+8", 'ans'=>"11"),
8=> array('no'=>8, 'ques'=>"3+9", 'ans'=>"12"),
9=> array('no'=>9, 'ques'=>"3+10", 'ans'=>"13"),
10=> array('no'=>10, 'ques'=>"3+11", 'ans'=>"14")
);
if (! isset($_GET["draw"])) {
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
}
$MathquesRand = array(); //New array to contain the 4 random rows
if (! isset($_GET["draw"]) ) {
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
}
?>
<?php
if (isset($_GET["draw"]) && $_GET["draw"] !="") {
$pieces = explode(",", $_GET["draw"]);
$index=0;
while ($index < count($pieces)) {
if ($pieces[$index]!=""){
$MathquesRand[] = $Mathques[$pieces[$index]];
}
$index++;
}
}
?>
<form action="" method="get">
<?php
$correct=0;
$wrong=0;
?>
<h1> Section : Mathematics </h1>
<p>Hello ! You may start your quiz !<p>
<hr>
<?php
$pool="";
$ii=1;
foreach ($MathquesRand as $qtsno => $value) {
$pool.= $value["no"]. ",";
?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans<?php echo $ii; ?>"
<?php if (isset($_GET["userans".$ii]))
{
echo " value='" .$_GET["userans".$ii] . "'>" ;
} else { echo ">" ; }
?>
<?php if (isset($_GET["userans".$ii]) && $_GET["userans".$ii]==$value["ans"]) {
$correct++;
} else {
$wrong++;
}
?>
<br>
<?php
$ii++;
}
?>
<input name=draw type=hidden value="<?php echo $pool; ?>">
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
$score = ($correct * 5) - ($wrong * 3);
?>
<?php if (isset($_GET["draw"])) { ?>
<font color=red>Result:</font>
<br>Correct:<?php echo $correct;?>
<br>Wrong:<?php echo $wrong;?>
<br>Score:<?php echo $score;?>
<?php } ?>
To share my experience (I have coded such Multiple Choice Q & A functions many times) , in future if you want to do similar thing, please consider using
database to store the drawn questions ;
use ajax to compare the input data with the correct data stored in the db, instead of using form submission
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 have an option menu as follows:
<select name="selCycle" id="selCycle" onChange="formFilter.submit()">
<option value="%">all cycles</option>
<?php
do {
?>
<option value="<?php echo $row_Recordset2['Cycle'] ?>"
<?php
if ($varCycle_DetailRS4 == $row_Recordset2['Cycle']) {
echo 'selected';
} elseif ($varCycle2_DetailRS4 == $row_Recordset2['Cycle']) {
echo 'selected';
} else {
echo '';
}
?>
>
<?php echo $row_Recordset2['Cycle'] ?>
</option>
<?php
} while ($row_Recordset2 = mysql_fetch_assoc($Recordset2));
$rows = mysql_num_rows($Recordset2);
if ($rows > 0) {
mysql_data_seek($Recordset2, 0);
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
}
?>
</select>
Currently, the default selection is showing all records. I would like for the default to be the latest set of data equal to:
<?php echo $row_RecordsetCycle['Cycle']; ?>
So option menu would list 1,2,3,4,5 with 5 being the default when the page loads. User can then pick any option available. is set to last record in table with a limit of 1 so it will always echo the last record, which composes the option menu.
Help please. What should I edit so that the one record in
<?php echo $row_RecordsetCycle['Cycle']; ?>
is the default or selected option menu when the page loads? Currently, the default just shows all records and is extremely slow to load, hence why I want the latest record to be the default.
I took a stab at rewriting this. (code at the end)
the first thing I did was turn your do_while loop into a while loop as I think it was adding unnecessary confusion to the code
after doing that I moved some code
$rows = mysql_num_rows($Recordset2);
if ($rows > 0) {
mysql_data_seek($Recordset2, 0);
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
}
above the while loop as I thought it was needed to "prime the pump" of the while loop
I also pulled the
if ($varCycle_DetailRS4 == $row_Recordset2['Cycle']) {
return ' selected';
} elseif ($varCycle2_DetailRS4 == $row_Recordset2['Cycle']) {
return ' selected';
} else {
return '';
}
out into a function so as to simplify the code further
now here come my assumptions I assumed that $varCycle_DetailRS4 was the last value and that $varCycle2_DetailRS4 was the currentlySelected that was set befor the code provided;
if that is the case and that $varCycle2_DetailRS4 would be unset if it was the first then all that would need to be done is to slightly modify the isSelected to only set one option as selected.
<?php
function isSelect($value)
{
$lastValue = $varCycle_DetailRS4;
$currentlySelected = $varCycle2_DetailRS4;
if(isset($currentlySelected))
{
$selectValue = $currentlySelected;
}
else
{
$selectValue = $lastValue;
}
if ($selectValue == $value) {
return ' selected';
} else {
return '';
}
}
?>
<select name="selCycle" id="selCycle" onChange="formFilter.submit()">
<option value="%">all cycles</option>
<?php
$rows = mysql_num_rows($Recordset2);
if ($rows > 0) {
mysql_data_seek($Recordset2, 0);
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
}
while ($row_Recordset2 = mysql_fetch_assoc($Recordset2))
{
$value = $row_Recordset2['Cycle']
echo " <option value=\"".$value."\"".isSelect($value).">".$value."</option>/n";
} ;
?>
</select>
Try using end() to get the last array:
<?php
$arr =array(1,2,3,4,5);
$last = end($arr);
?>
<select name="selCycle" id="selCycle" onChange="formFilter.submit()">
<option value="%">all cycles</option>
<?php foreach($arr as $key=>$val):
if(in_array("$last", array($val))==true){
echo '<option value="" selected="selected">'.$val.'</option>';
continue;
}
echo '<option>'.$val.'</option>';
endforeach; ?>
</select>
Stop using mysql extension, use pdo or mysqli. Using your question code, it should be:
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
$last = end($row_Recordset2);
foreach($row_Recordset2 as $key=>$val){
//other code
if(in_array("$last", array($val))==true){
echo '<option value="" selected="selected">'.$val.'</option>';
continue;
}
echo '<option>'.$val.'</option>'
}
Working Demo
My main issue is the number of times I query the database (see below). Also, I would like to check that the current product (optionsToProducts.productID) has options for the current optionName before outputting the select statement! See the final image below to see the blank select box...
I have 8 tables in total, but the 3 that matter are:
optionNames
http://www.grabb.co.uk/stack/001.png
productOptions
http://www.grabb.co.uk/stack/002.png
optionsToProducts
http://www.grabb.co.uk/stack/003.png
<?php
$i=0;
$optionsquery = "SELECT * FROM optionNames WHERE categoryID = ".$categoryID."";
$optionsresult= mysql_query($optionsquery) or die(mysql_error());
while ($optionnames = mysql_fetch_array($optionsresult)) {
$i++;
$optionname = $optionnames["optionName"];
$optionID = $optionnames["optionNamesID"];
//echo $optionname."<br />";
?>
<label for="option<?php echo $i; ?>"><?php echo $optionname; ?></label>
<select name="option<?php echo $i; ?>" id="<?php echo $i; ?>">
<?php
//$optionvalues = "SELECT * FROM (optionsToProducts,productOptions) WHERE optionsToProducts.productID = ".$productID." AND productOptions.optionNamesID = ".$optionID."";
//echo $optionvalues."<br /><br />";
$optionvalues = "SELECT * FROM optionsToProducts WHERE productID = ".$productID."";
$valuesresult= mysql_query($optionvalues) or die(mysql_error());
while ($optionvals = mysql_fetch_array($valuesresult)) {
$valueName = $optionvals["optionValue"];
$valueID = $optionvals["productOptionsID"];
//echo $valueName."<br />";
$optionfinal = "SELECT * FROM productOptions WHERE productOptionsID = ".$valueID." AND optionNamesID = ".$optionID."";
$finalresult= mysql_query($optionfinal) or die(mysql_error());
while ($optionlast = mysql_fetch_array($finalresult)) {
$optionValueName = $optionlast["optionValue"];
$optionValueID = $optionlast["productOptionsID"];
$num_rows = mysql_num_rows($finalresult);
?>
<option value="<?php echo $optionValueID; ?>"><?php echo $optionValueName; ?></option>
<?php
}
}
echo "</select>";
}
?>
final Output:
http://www.grabb.co.uk/stack/004.png
As always, your help is appreciated. Thank you.
Since you tagged this question with the join tag, you probably know you need to write a join query to get what you need.
<?php
$i=0;
$query = "SELECT options.optionName, options.optionNamesID, po.optionValue, po.productOptionsID
FROM optionNames AS options
INNER JOIN productOptions AS po ON po.optionNamesID=options.optionNamesID
INNER JOIN optionsToProducts AS otp ON otp.productOptionsID=po.productOptionsID
WHERE otp.productID=" . (int) $productID
. " AND options.categoryID=" . (int) $categoryID;
$result = mysql_query($query);
if($result) {
$rows = array();
while($row = mysql_fetch_assoc($result) ) {
$rows[] = $row;
}
$i = 0;
$optionId = null;
foreach($rows as $row) {
if($optionId != $row['optionNamesID']) {
$optionId = $row['optionNamesID'];
?>
<label for="option<?php echo $optionId; ?>"><?php echo $row['optionName']; ?></label>
<select name="option<?php echo $optionId; ?>" id="<?php echo $optionId; ?>">
<?php } ?>
<option value="<?php echo $row['productOptionsID']; ?>"><?php echo $row['optionValue']; ?></option>
<?php
//Close select element when the optionNamesID changes or on the last row
if( (isset($rows[$i + 1]) && $rows[$i + 1]['optionNamesID'] != $optionId) ||
!isset($rows[$i + 1]) ) { ?>
</select>
<?php }
$i++;
}
} else {
//Debug query, remove in production
echo mysql_error();
}
?>
I also made some small changes - I use the optionNamesID in the select and label tag names - I don't know how you knew previously which select belonged to which option.
I also assumed that categoryID and productID came from somewhere, since it's not specified in the code.
Pushing all the rows to an array at the beginning is optional, but it makes the code a bit more organized (since you can check ahead in the array to see where to close the select tags).
NOTICE - this code is untested so there could some minor typos. Please make the needed corrections if necessary.
I am trying to code a function which creates a dropdown of school names selected from a database. It is doing fine creating a dropdown but it is not putting anything in the dropdown. Here is the code:
function schoolDD($name, $selected){
$select = '';
if( $selected != null )
{
$select = $selected;
}
$qry = "select *
from school
order by name, id
where display = 'Y'";
$schools = _execQry($qry);
$html = '<select name="'.$name.'" >';
foreach( $schools as $s ){
$html .= '<option value="'. $s['id'] .'"';
if( $select == $s['name'] ){
$html .= 'selected="selected"';
}
$html .= '>'. $s['name'] . '</option>';
}
$html .= '</select>';
return $html;
}
Problem solved. It was because in the query I had order before where. It should have been:
$qry = "select *
from school
where display = 'Y'
order by name, id";
Not:
$qry = "select *
from school
order by name, id
where display = 'Y'";
Looks OK but hard to say without knowing what _execQry does.
If you add the line
print_r($schools);
after you call _execQry, are you definitely retrieving results from the database?
Im glad you found your answer, but i haaattee php and html mixed together like that.
what about tsomethign like this...
<?php
$schools = getSchools();
$selectedSchool = 'sfgsfgd';
$name = 'asdfsafd';
?>
<select name="<?= $name ?>">
<?php foreach( $schools as $s ): ?>
<option value="<?= $s['id'] ?>"<?php if( $s['name'] == $selectedSchool ): ?> selected="selected"<?php endif; ?>><?= $s['name'] ?></option>
</select>