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
Related
I have two List Boxes and I click on both of them to create the SELECT query.I placed the $POST variable into another variable and then placed these into the select query.This seems to work fine,but the problem arises when I only want to select from one of the boxes for example just all of Ken Davis's books or all books from the adventure genre.It seems I have to chhose both boxes before I get a result.Can anyone suggest a way round this
<html>
<head>
<title>My Page</title>
</head>
<body>
<br>
<form name="myform" action="dropdown2.php" method="POST">
<select name="author" size="4">
<option value="ken davies">ken davies</option>
<option value= "arthur smith">arthur smith</option>
<option value="gill rafferty">gill rafferty</option><br />
<option value="molly brown">molly brown</option><br />
<option value="gilbert riley">gilbert riley</option><br />
<input type = "submit" name = "submit" value = "go">
<select name="genre" size="4">
<option value="adventure">adventure</option>
<option value="biography">biography</option>
<option value="crime">crime</option><br />
<option value="romance">romance</option>
<option value="2007">thriller</option>
<input type = "submit" name = "submit" value = "go">
<?php
$_POST['author'];
$bird = $_POST['author'];
$_POST['genre'];
$cat = $_POST['genre'];
$con = mysql_connect("localhost","root","");
If (!$con){
die("Can not Connect with database" . mysql_error());
}
Mysql_select_db("authors",$con);
$sql = "SELECT * FROM books WHERE author = '$bird' AND genre = '$cat' ";
$myData = mysql_query($sql,$con);
echo"<table border=1>
<tr>id</th>
<tr>author</th>
<tr>title</th>
<tr>publisher</th>
<tr>year</th>
<tr>genre</th>
<tr>sold</th>
</tr>";
while($record = mysql_fetch_array($myData)){
echo "<tr>";
echo "<td>" . $record['id'] . "</td>";
echo "<td>" . $record['author'] . "</td>";
echo "<td>" . $record['title'] . "</td>";
echo "<td>" . $record['publisher'] . "</td>";
echo "<td>" . $record['year'] . "</td>";
echo "<td>" . $record['genre'] . "</td>";
echo "<td>" . $record['sold'] . "</td>";
echo "<tr />";
}
echo "</table>";
mysql_close($con);
?>
</form>
</body>
</html>
If you want to filter by only author or only genre, change the logic leading up to your SQL.
if (isset($bird) && isset($cat))
$sql = "SELECT * FROM books WHERE author = '$bird' AND genre = '$cat' ";
elseif (isset($bird))
$sql = "SELECT * FROM books WHERE author = '$bird' ";
elseif (isset($cat))
$sql = "SELECT * FROM books WHERE genre = '$cat' ";
Also I'm legally required to let you know that putting variables in SQL will lead to SQL injection. You should prepare and execute. I'll write some example code below (one sec).
First you need to get the values from the form like you are doing, but you need to add in some code that allows them to be non-mandatory:
$bird = ( ! empty($_POST['author'])) ? $_POST['author'] : null;
$cat = ( ! empty($_POST['genre'])) ? $_POST['genre'] : null;
This will either give you the value that was submitted with the form, or null which can be used later to decide how to query your db. I would also suggest you check the values given match what you expect. So either compare the data to known authors, or known genres and weed out tampered data, e.g:
$genres = array('adventure', 'biography', 'crime', 'romance', 'thriller');
if ( ! in_array($cat, $genres)) {
// invalid data supplied (you could show an error)
unset($cat); // destroys the invalid variable
}
Then when you come to your db query you can do something like this:
if (isset($bird) && isset($cat)) {
// SELECT by both
}
else if (isset($bird)) {
// SELECT by author
}
else if (isset($cat)) {
// SELECT by cat
}
else {
// SELECT all
}
There are many ways to shorten the above, but this is a good starting point for you.
In such a case, you will have to write separate queries in your PHP code for separate cases.
//When both the list boxes are selected
if(isset($_POST['author'])&&isset($_POST['genre']))
{
$sql = "SELECT * FROM books WHERE author = '$bird' AND genre = '$cat' ";
unset($_POST['genre']);
unset($_POST['author']);
}
//When searching genre-wise (author variable not set)
elseif(!isset($_POST['author']))
{
$sql = "SELECT * FROM books WHERE genre = '$cat' ";
unset($_POST['genre']);
}
//When searching authorwise (genre variable not set)
elseif(!isset($_POST['genre']))
{
$sql = "SELECT * FROM books WHERE author = '$bird'";
unset($_POST['author']);
}
I am facing difficulties while selecting values from drop down list based on the selected value from another drop down list that too retrieve from sql database
My PHP code is embedded with html, here is the code i am trying to do with select:
Country Name: <select name="status" style="width: 150px;">
<option value="select_country" selected>select</option>
<?php
$c_id="";
include 'dbconfig.php';
$sql = "select * from Country";
$result = sqlsrv_query($conn,$sql);
while($row = sqlsrv_fetch_array($result))
{
echo("<option value = '" . $row['Country'] . "'>" . $row['Country'] . " </option>");
$c_id=$row['CountryId'];
}
?>
</select> Create New Country
<br /><br />
State Name: <select name="status" style="width: 150px;" >
<option value="select_State" selected>select</option>
<?php
$s_id="";
$sql = "select * from State where CountryId = $c_id";
$result = sqlsrv_query($conn,$sql);
while($row = sqlsrv_fetch_array($result))
{
echo("<option value = '" . $row['State'] . "'>" . $row['State'] . " </option>");
$c_id=$row['State'];
}
?>
</select> Create New State
Please suggest me how to overcome this and thanks in advance..
You should use AJAX if you want the second select shown options based on the first option list picked value.
You have to use JAAX upon selection of first drop down list and replace the options of second drop down list.
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.
I created a database with 3 tables being spusername, splocation, sprecord. spusername has id, splocation_id, lastname, firstname. I want to be able to have a drop down menu that has pulled id, lastname, firstname from the database, and within the pulldown it only shows a list of all the names being lastname,firstname. then once I select a person I have another drop down that has types of training in it. then when I hit submit it will generate a record in another table with the persons id and training record. so when I do a search it will pull up the user and the training records for that person.... I have already created a submit page in a .php that sends lastname, firstname, splocation_id for new users and I think I can create a search that does what I want it to, but I have never made a data entry doing a pulldown that has values generated from the database.
EDIT Code: With help from Vegard's coding I got this, and now it works great after a few trial and errors. Thank You!
Code:
<?php
if (isset($_REQUEST['Submit'])) {
$sql = "INSERT INTO $db_table(spusername_id,sptraining_id) values ('".mysql_real_escape_string(stripslashes($_REQUEST['spusername_id']))."','".mysql_real_escape_string(stripslashes($_REQUEST['sptraining_id']))."')";
if($result = mysql_query($sql ,$db)) {
echo '<h1>Thank you</h1>Your information has been entered into the database<br><br>';
} else {
echo "ERROR: ".mysql_error();
}
} else {
?>
<h1>Add Training Information To Database</h1><hr>
<br><br>
<form method="post" action="">
<select name="spusername_id">
<option value="default">Select Employee</option>
<?php
include("connectspusers.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, lastname, firstname FROM spusername ORDER BY lastname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . ' ' . $row['lastname'] . ' ' . $row['firstname'] . '">' . $row['lastname'] . ', ' . $row['firstname'] . '</option>';
}
?>
</select>
<select name="sptraining_id">
<option value="default">Select Training</option>
<?php
include("connectsptraining.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, trainingtype, level FROM sptraining ORDER BY level ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . ' ' . $row['trainingtype'] . ' ' . $row['level'] . '">' . $row['trainingtype'] . ' - ' . $row['level'] . '</option>';
}
?>
</select>
<br><br>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
}
?>
Something like this?
<select name="pulldown1">
<option value="default">Choose an option</option>
<?php
include("connect.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, lastname, firstname FROM spusername ORDER BY firstname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . htmlentities($row['id'], ENT_QUOTES) . ' ' . htmlentities($row['lastname'], ENT_QUOTES) . ' ' . htmlentities($row['firstname'], ENT_QUOTES) . '">' . htmlentities($row['lastname'], ENT_QUOTES) . ', ' . htmlentities($row['firstname'], ENT_QUOTES) . '</option>';
}
?>
</select>
<select name="pulldown2">
<option value="default">Choose and option</option>
<?php
$result = mysql_query('SELECT traingtype FROM trainingtable ORDER BY trainingname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['trainingtype'] . '">' . $row['trainingtype'] . '" "' . $row['lastname'] . '</option>';
}
?>
</select>
This will result in two dropdown menus where the first dropdown lists the users last- and firstname separated by a comma+space and the second will list the different types of training. The ID filed is only sendt via the variable, but not displayed to the user.
When pulling the values from the variable in pulldown1, just use explode:
$userdetails = $_POST['pulldown1'];
$values = explode(" " $userdetails);
$ID = $values[0];
$lastname = $values[1];
$firstname = $values[2];
Haven't tested the code so it might need tweaking, and ofcourse you need to change the variable names corresponding to your actual db rownames.
Edit: In your code, you have to use $row and not $row2.
Secondly, instead of this:
<option value='{$id}'>{$lastname},{$firstname}</option>
use this:
<option value="' . $row['id'] . '">' . $row['lastname'] . ', ' . $row['firstname'] . '</option>
<select name="id" size="1">
<?php
$result=mysql_query("select * from spusername;");
while($user=mysql_fetch_array($result)) {
echo "<option value=\"".$user['id']."\">".$user['lastname'].", ".$user['firstname']."</option>";
?>
</select>
Go on with always using "id" as a reference to the user and try using post instead of get to send the request(keeps the URL in your user's browser clean).
You build a select in a loop with the data from your database.
example with mysql (did not test):
$query = "select id, lastname, firstname from spusername";
$result = mysql_query($query);
echo "<select>";
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['id']."'>".$row['lastname']. " ". $row['firstname']."</option>";
}
echo "</select>";
EDIT: (response to your edit)
In your code you use $row2 instead of $row
Just an addendum to Vegard's solution:
Single quotes can be a bit tricky with surnames. It really depends on how you're storing the data in your database though.
If you have a surname O'Leary or O'Reilly you might get truncated results as you're building your select loop on the names. Give it a try.
You can fix this issue by using
htmlentities($row['lastname'], ENT_QUOTES) in your select loop
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.