How to retrieve data from all options if user selects `All` - php

Got a mysqli/php code below where it will display results depending on option selected from the question drop down menu:
$selectedquestionqry = "
SELECT
QuestionNo
FROM
Question
WHERE
(QuestionId = ?)
";
global $mysqli;
$selectedquestionstmt=$mysqli->prepare($selectedquestionqry);
// You only need to call bind_param once
$selectedquestionstmt->bind_param("i",$_POST["question"]);
// get result and assign variables (prefix with db)
$selectedquestionstmt->execute();
$selectedquestionstmt->bind_result($selQuestionNo);
$selectedquestionstmt->store_result();
$selquestionnum = $selectedquestionstmt->num_rows();
while ($selectedquestionstmt->fetch()) {
if($_POST["question"] === '0') {
echo "<p>All Questions - Total:(" . $selquestionnum . ")</p>" . PHP_EOL;
}else if($_POST["question"] !== '0') {
echo "<p><strong>Questions: </strong>" . $selQuestionNo . "</p>" . PHP_EOL;
}
}
DROP DOWN MENU:
<select name="student" id="studentsDrop">
<option value="0">All</option>
<option value="23">Jay Hart</option>
<option value="32">Bubba Wright</option>
</select>
My question is that how can I get it so that if the user has selected '0', then it will be able to select all questions from the db which are displayed in the question drop down menu?
The reason I am asking this is because in my echo else if($_POST["question"] !== '0') {
echo "<p><strong>Questions: </strong>" . $selQuestionNo . "</p>" . PHP_EOL;
}, nothing is being echo when I select the All option, which to me makes me think that it is not displaying the echo due to this. If I select a single question from drop down menu, it is able to output it's echo.

you just need to modify your query:
if($_POST["question"] === '0') {
$selectedquestionqry = "SELECT QuestionNo FROM Question";
} else {
$selectedquestionqry = "SELECT QuestionNo FROM Question WHERE (QuestionId = ?)";
}

You need to change your query to remove the WHERE condition based the posted value being '0'. You shouldn't have to change any of your code after that since you're already looping, but you should display the Total outside of the loop.

Related

Retain Value of Select Tag after Submit - PHP

I'm trying to add subject to a teacher's workload. I have a validation before inserting the user input to my workload table, mostly for detecting schedule conflict.
Now, what I want is to retain the selected value of the user and display it again after the validation fails. So that the user doesn't have to select the subject name, class name, and class adviser again.
I've attached my code for the class adviser selection.
<?php
$link = mysqli_connect("localhost", "root", "", "smis");
$sql = "SELECT * FROM teacherData";
$result = mysqli_query($link,$sql);
echo "<select id='modalINPUT' name='teacherID' required>";
echo"<option value=''>Select Adviser</option>";
while ($row = mysqli_fetch_array($result))
{
echo "<option value='".$row['teacherID']."'>".$row['Fname'] ." ". $row['Mname'] ." " .$row['Lname'] . "</option>";
}
echo "</select>";
?>
/*
Once validation fails, is there a way where I can display the selected value?
Like display the name of the teacher.
*/
Yes, you can use:
$teacherID = !empty($_POST['teacherID']) ? $_POST['teacherID'] : '';
right before your sql query
Then to display selected value on select box, you can check if posted id matches with current id and print out selected parameter for the according option field:
echo '<option value="'.$row['teacherID'].'"'.($teacherID == $row['teacherID'] ? ' selected="selected"' : '').'>'.htmlspecialchars($row['Fname']) .' '. htmlspecialchars($row['Mname']) .' ' .htmlspecialchars($row['Lname']) . '</option>';
EDIT: Take a look on my edited answer - use single quotes for better performance (so PHP doesnt have to scan your double quoted string for vars), and ALWAYS process your information, which you get from DB with htmlspecialchars, so you don't mess up your html, when something improper is saved into DB
EDIT: Also do not select all data from MYSQL table, unless you need to. To gain performance, select only fields you need in your query:
$sql = 'SELECT teacherID, Fname, Mname, Lname FROM teacherData';
You could compare the posted value against the id of the current row. And add selected attribute if the values are the same.
// create $selected variable to get "selected" or "":
$selected = isset($_POST['teacherID']) && $_POST['teacherID'] == $row['teacherID']
? 'selected' : '' ;
// add $selected to the <option> tag:
echo "<option value='".$row['teacherID']."' $selected>"
. $row['Fname'] ." ". $row['Mname'] ." " .$row['Lname']
. "</option>";

dynamically populate mysql array into drop down menu

I have a database that I want to get data out onto a website. It contains states listed by name and id. Counties listed by id, namne , and state that contains thems ID and then clubs that exist , with a reference to the county id's that they exist in and columns for their actual data.
What I've got :
A drop down menu that populates itself with state id and name.
What I'd like to accomplish:
On selection of state , let's say ny , take it's id and use this in gathering another mysql array for the county drop down. I'd like it to dynamically occur on selection of state , maybe even giving a count of results next to the drop down.
$resstate = mysql_query("SELECT * FROM state ORDER by longstate;") or die("Note: " . mysql_error());
State:
<select name="State" size=1>
<?
while( $rs = mysql_fetch_array( $resstate ) ) {
echo "<option value=" .$rs['id'] . ">" . $rs['longstate'] . "</option>";
}
echo "</select>";
?>
I know I could use a JavaScript onChange="this.form.submit()" on the first drop down, but it's my understanding that I'd then be making a new page at that point and don't know if I could keep the functionality of the state drop down, say if you accidentally chose new Hampshire when you wanted New York.
here's an example of the current array filling the drop down :
http://snowmobileamerica.com/countytest.php
----EDIT---
Using Dagons Advice , I looked into Ajax.
I made a php file that's supposed to query the database based on a reference to getcounty.php?q=
The file is created as follows :
<?php
$q=$_GET["q"];
$cn=mysql_connect("localhost","user","password") or die("Note: " . mysql_error());
mysql_select_db("snowusa_clubs", $cn);
$sql="SELECT * FROM county WHERE state_id = '".$q."' ORDER by name";
$result = mysql_query($sql);
echo "<select name="County" size=1>";
while($rc = mysql_fetch_array($result))
{
echo "<option value=" .$rc['id'] . ">" . $rc['name'] . "</option>";
}
echo "</select>";
mysql_close($cn);
?>
If i try to run it manually http://www.snowmobileamerica.com/getcounty.php?q=33 I get a 500 internal server error...
Any ideas where I went wrong?
try adding an id to the element, then make an ajax call to a handler with jquery:
$("#State").change(function() {
$.post("path/to/request handler/" , { "State" : $(this).val() },
function(data){
if (data == "OK"){
//add some elements here
} else {
//handle an error here
}
});
});
not able to comment yet.
but for the second question try:
<?php
$q=$_GET["q"];
$cn=mysql_connect("localhost","user","password") or die("Note: " . mysql_error());
echo "Conn ok<br>";
mysql_select_db("snowusa_clubs", $cn);
echo " Database opened<br>";
$sql="SELECT * FROM county WHERE state_id = '$q' ORDER by name";
$result = mysql_query($sql);
echo " Database queried <br>";
echo "<select name='County' size=1>";
while($rc = mysql_fetch_array($result))
{
echo "<option value='" .$rc['id'] . "'>" . $rc['name'] . "</option>";//added single quotes in the value
}
echo "</select> ";
mysql_close($cn);
?>

echo not appearing when selecting a certain value

I have a assessment drop down menu below:
<select name="session" id="sessionsDrop">
<option value="All">All</option>
<option value="2">EOWOW</option>
<option value="34">EOWOW</option>
</select>
<select name="student" id="studentsDrop">
<option value="All">All</option>
<option value="23">Jay Hart</option>
<option value="32">Bubba Wright</option>
</select>
Above is a simple drop down menu. I run a query below to get a selected student's details as well as get the selected assessment details. Now the selected assessment outputs the details fine with no problem, But the echo for selected student option does not work as if the user selects the All option, then echo "<p><strong>Students: </strong>All Students - Total:(" .$selstudentnum . ")</p>" . PHP_EOL;. But the problem is that it does not display this echo if the All option is chosen. In fact it does not display an echo at all if the All option is chosen. I tried both === and == bu can't see what I am doing wrong
$selectedsessionqry = "
SELECT
SessionName, SessionDate, SessionTime
FROM
Session
WHERE
(SessionId = ?)
";
global $mysqli;
$selectedsessionstmt=$mysqli->prepare($selectedsessionqry);
// You only need to call bind_param once
$selectedsessionstmt->bind_param("i",$_POST["session"]);
// get result and assign variables (prefix with db)
$selectedsessionstmt->execute();
$selectedsessionstmt->bind_result($selSessionName,$selSessionDate,$selSessionTime);
while ($selectedsessionstmt->fetch()) {
echo "<p><strong>Assessment: </strong>" . $selSessionName . " - " . date('d-m-Y',strtotime($selSessionDate)) . " - " . date('H:i',strtotime($selSessionTime)) . "</p>" . PHP_EOL;
}
$selectedsessionstmt->close();
$selectedstudentqry = "
SELECT
StudentAlias, StudentForename, StudentSurname
FROM
Student
WHERE
(StudentId = ?)
";
global $mysqli;
$selectedstudentstmt=$mysqli->prepare($selectedstudentqry);
// You only need to call bind_param once
$selectedstudentstmt->bind_param("i",$_POST["student"]);
// get result and assign variables (prefix with db)
$selectedstudentstmt->execute();
$selectedstudentstmt->bind_result($selStudentAlias,$selStudentForename,$selStudentSurname);
$selectedstudentstmt->store_result();
$selstudentnum = $selectedstudentstmt->num_rows();
while ($selectedstudentstmt->fetch()) {
if($_POST["student"] === 'All') {
echo "<p><strong>Students: </strong>All Students - Total:(" .$selstudentnum . ")</p>" . PHP_EOL;
}else{
echo "<p><strong>Students: </strong>" . $selStudentAlias . " - " . $selStudentForename . " " . $selStudentSurname . "</p>" . PHP_EOL;
}
}
I think your condition fails here
$selectedstudentstmt->bind_param("i",$_POST["student"]);
Its expecting integer value but you are sending string.
Don't use $_POST directly in your query.It will cause sql injection attack.
Sanitize the user input before use it in sql queries.
Changes:
Add the below conditions before your query. Once again don't forget to sanitize.
if ($_POST["student"] == 'ALL') {
$where = WHERE (StudentId = ?) ";
} else {
$where = "";
}
$selectedstudentqry = " SELECT StudentAlias, StudentForename, StudentSurname FROM Student $where

PHP Dropdown of all records from database + select current set record

I have a PHP dropdown of a list of groupnames (together with id, so it can be updated). In this FORM page you can change the groupname specified for an item by choosing possibilities from the dropdown coming out from the database. My code below works, but there must be a better way, because I get the first field as the currently set, and then all the possibilities, so I get this record twice.
Example:
- Keyboard (Currently set)
- Speakers (Possible to choose, straight from DBS)
- Midi Controllers (Possible to choose, straight from DBS)
- Keyboard (Possible to choose, straight from DBS)
- Drum set (Possible to choose, straight from DBS)
As you see I get the currently set record again.
My code:
echo "<select name='itemgroupid'>";
// CHOOSE CURRENT SET RECORD AS SELECTED ITEM
echo "<option value='" . $itemgroupid . "'>";
$selected="
SELECT item.itemid, itemgroup.itemgroupname, itemgroup.itemgroupid
FROM item, itemgroup
WHERE item.itemid=$itemid";
$selectedresult=mysql_query($query) or die("query fout " . mysql_error() );
while($record=mysql_fetch_array($selectedresult) ) {
echo "" . $itemgroupname . "</option>";
}
// QUERY TO SHOW ALL POSSIBLE CHOOSABLE RECORDS FROM DATABASE
$itemgroupquery="SELECT itemgroupname,itemgroupid FROM itemgroup";
$itemgroupqueryresult = mysql_query ($itemgroupquery);
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option value=$nt[itemgroupid]>$nt[itemgroupname]</option>";
}
echo "</select>";
There are 2 ways to achieve what you're looking for:
1) To show the selected item at the top of the dropdown
echo "<select name='itemgroupid'>";
// CHOOSE CURRENT SET RECORD AS SELECTED ITEM
echo "<option value='" . $itemgroupid . "'>";
$selected="
SELECT item.itemid, itemgroup.itemgroupname, itemgroup.itemgroupid
FROM item, itemgroup
WHERE item.itemid=$itemid";
$selectedresult=mysql_query($query) or die("query fout " . mysql_error() );
while($record=mysql_fetch_array($selectedresult) ) {
echo "" . $itemgroupname . "</option>";
}
// QUERY TO SHOW ALL POSSIBLE CHOOSABLE RECORDS FROM DATABASE
$itemgroupquery="SELECT itemgroupname,itemgroupid FROM itemgroup WHERE item.itemid != $itemid";
$itemgroupqueryresult = mysql_query ($itemgroupquery);
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option value=$nt[itemgroupid]>$nt[itemgroupname]</option>";
}
echo "</select>";
2) Show the selected item in it natural place
echo "<select name='itemgroupid'>";
// QUERY TO SHOW ALL POSSIBLE CHOOSABLE RECORDS FROM DATABASE
$itemgroupquery="SELECT itemgroupname,itemgroupid FROM itemgroup";
$itemgroupqueryresult = mysql_query ($itemgroupquery);
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option value=$nt[itemgroupid]";
if( $itemid == $nt['itemgroupid'] ) echo ' selected="selected"';
echo ">$nt[itemgroupname]</option>";
}
echo "</select>";
HTH
OK
In your code.
rather than output your selected value at the top, do it the proper way :)
Select your current item (make a note of the itemgroupid for example)
then in your output
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option ";
if ($savedid==$nt[itemgroupid]) echo "selected ";
echo "$nt[itemgroupid]>$nt[itemgroupname]</option>";
}
echo "</select>";
This will produce with $savedid=1
<option value=0>group 0</option>
<option selected value=1>group 1</option>
<option value=2>group 2</option>
Add the default selected record to a empty array first like
toDisplay = array('selected_record');
Then, get the data from the database using your sql and append it to this array.
Later run a array_unique on it and finally using a loop create the html output string, in the same way you are doing it now.

Method for initializing selectmenu to certain value?

I have a screen that shows users a list of players and the grades users have given them. By clicking on a button, they can select from a list of players and grade these players themselves.
I want to streamline this process by allowing users to simply click on a player name where it goes to the grading page with the select menu already initialized to the player's name that they just clicked on.
Is there a way to initialize a select menu to a certain value?
Here is the mySQL query:
$query = #mysql_query('SELECT person.firstname, person.lastname, person.id FROM person inner join player ON player.person_id=person.id WHERE player.team_id=' . $homeid . ' ORDER BY lastname asc');
And the code that creates the select menu:
<select name='id'>
<?php
while ($temp = mysql_fetch_assoc($query)) {
echo "<option value=" . $temp['id'] . ">" . htmlspecialchars($temp['firstname']) . " " . htmlspecialchars($temp['lastname']) . "</option>";
}
?>
</select>
of course ,,, The option you want to be selected should contain the attribute selected
if //bla bla this is the one
echo "<option selected=\"selected\" value=" . $temp['id'] . ">" . htmlspecialchars($temp['firstname']) . " " . htmlspecialchars($temp['lastname']) . "</option>";
else
echo "<option value=" . $temp['id'] . ">" . htmlspecialchars($temp['firstname']) . " " . htmlspecialchars($temp['lastname']) . "</option>";
if (currentId == $temp['id']) <option selected>...</option>
else <option>...</option>
If you have a value called $id you can:
echo '<option value="'.$temp['id'].'" '.($temp['id'] == $id ? 'selected="selected"' : '').'>'.htmlspecialchars($temp['firstname']).' '.htmlspecialchars($temp['lastname']).'</option>';
Difference:
($temp['id'] == $id ? 'selected="selected"' : '')
The selected attribute on a preselects this value upon loading the page.
I Hope understood your question.

Categories