in PHP get variable from SELECT OPTION value from HTML - php

I have looked at this answer enter link description here
but I am not able to make my code work, this is what i have in my selectcategory.php file. I want to have this variable $selectedcategory set up in this file. Echo command at the bottom is for testing purpose only.
My code:
<?php
include_once('config.php');
$query1 = mysqli_query($query, "SELECT category FROM `events` GROUP BY category");
echo "<select name'selectedcategory'>";
while ($row = mysqli_fetch_assoc($query1)){
echo "<option value='".$row['category']."'>".$row['category']."</option>";
}
echo "</select>";
$selectedcategory=$_POST['selectedcategory'];
echo $selectedcategory;
?>
Where do I make mistake? In other files I have taken variable by this POST method from INPUT or SELECT element with given name. In this file Error is on line 10 - UNDEFINIED VARIABLE, so where do I make mistake in getting it?
Thank you in advance and if more clarification needed, please ask.
ps: I know my code has mistakes, but please concentrate only on getting the variable now. In other questions on this forum people just comment that my code is for example vulnerable for injections but no new information to the question itself or to prevent this injection (problem identified by commenter), I would like to prevent that.
Identifing problem by commenter is great way of learning, but please than also provide some arguments why it is a problem or some links which relate to the problem.

Your form fields/values are not stored in $_POST array until after you submit the form.
You will need to wrap your select field in <form method="POST"></form> and provide a submit button to even get started with this process.
Start reading: https://www.w3schools.com/tags/att_form_method.asp
If you are submitting to the same page, you may want to use something like this:
include_once('config.php'); // labeling your connection '$query' doesn't seem like good practice and may trip you up in the future.
$result=mysqli_query($db,"SELECT category FROM `events` GROUP BY category");
if(isset($_POST['selectedcategory'])){
$selected=$_POST['selectedcategory'];
}else{
$selected="";
}
echo "<form action=\"\" method=\"POST\">";
echo "<select name=\"selectedcategory\">";
echo "<option></option>";
if($result){
while($row=mysqli_fetch_assoc($result)){
echo "<option value=\"{$row['category']}\"",($selected==$row['category']?" selected":""),">{$row['category']}</option>";
}
}
echo "</select>";
echo "<input type=\"submit\" value=\"Submit\">";
echo "</form>";
....
I understand that for someone new to php, an inline condition statement is pretty difficult to read.
Here is what it looks like over multiple lines:
echo "<option value=\"{$row['category']}\"";
if($selected==$row['category']){
echo " selected"; // only mark this option as "selected" if values match
}else{
echo ""; // otherwise, do not mark it with "selected"
}
echo ">{$row['category']}</option>";
If someone ever managed to POST a value that doesn't match any of the database values in the loop, then none of the <option>s would get the select attribute, and the <select> would show the first/top <option> by default.

Related

php populate option box from database table

I am writing code to register a new project via a html form. I want to be able to click a dropdown box which pulls the values from a table on the database.
At the moment a dropdown box displays but with no values.
PLEASE NOTE: I am a learning the basics so apologies if this is a simple question/answer scenario.
My code is below, any help is appreciated, I connect to the database via a php include script. The table is called 'customers' and the item I want to list is 'name';-
<?php
$result = mysql_query("SELECT customers FROM name");
echo "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row[name]."'>".$row[name]."</option>";
}
echo "</select>";
?>
"The table is called 'customers' and the item I want to list is 'name';" -
Do SELECT name FROM customers instead of SELECT customers FROM name
Using mysql_error() to mysql_query()
would have shown you the error that the table name does not exist.
Plus,
[name] are missing quotes inside them => ['name'] which are being treated as constants.
in
echo "<option value = '".$row[name]."'>".$row[name]."</option>";
as caught and kudos to devdesign
echo "<option value = '".$row['name']."'>".$row['name']."</option>";
However, you are using a deprecated MySQL library. If you are still not getting results, then this could mean that you need to use (and should use) mysqli_ or PDO instead.
Here are a few links on the subject:
mysqli with prepared statements
PDO with prepared statements.
Your code should be. Also note the single quotes within $row['name']. You missed that.
<?php
$result = mysql_query("SELECT name FROM customers");
echo "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row['name']."'>".$row['name']."</option>";
}
echo "</select>";
?>

Posting a value from Dropdown List from PHP div page

I'm having an issue in passing a value from a dropdown list that is in a separate PHP file that is being used by jquery.
I ended up getting the values from the dropdown list that isn't posting correctly by using jquery based on the value selected in the first dropdown list. The dropdown list in question is populating correctly, but with the way I have it setup I cannot post the value to the submit PHP page.
I'm pretty sure it has to do with the way I have it setup; however, I'm very new to jquery and was looking for some guidance.
The main PHP Page (the small areas in question)
<select name="department_list" id="department_list" onchange="$('#singleUser').load('get_users.php?nid='+this.value);">
...
<div id="singleUser" class="singleUser">
</div>
The PHP page (get_users) used to fill the values (only the area in question)
echo '<p style="text-align:center">';
echo "
<br />
Select a person to receive the form
<br />";
echo "<select id='userSelect' class='userSelect'>";
if ($id == '50') {
echo "<option value='Done'>Done</option>";
echo "</select>";
}else {
echo "<option value='none'>Select user</option>";
try {
$db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stmt = $db->prepare("SELECT dm.empid AS empid, u.name AS name FROM mytable dm
JOIN mytable2 u ON dm.empid = u.id
WHERE dm.deptid = :id
ORDER BY u.name");
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($r = $stmt->fetch()) {
$empid = $r['empid'];
$userName = $r['name'];
echo "<option value='".$empid."'>".$userName."</option>";
}
echo "</select>";
echo "</p>";
$db = null;
}
catch (PDOException $ex) {
echo "An Error occurred!";
}
}//end else
In the submit page:
if(isset($_POST['userSelect'])){
$givenID = $_POST['userSelect'];
//the rest of my code
I do have the div code above within the form tags and have method="post". All of my other inputs post correctly, so I'm thinking it has to do with the way I have only the div tags within the main page. Again, I'm pretty new to all of this so any ideas or changes that I should make so it posts correctly would be greatly appreciated.
You forgot the name of the select when you write it with php:
change this:
echo "<select id='userSelect' class='userSelect'>";
to
echo "<select id='userSelect' name='userSelect' class='userSelect'>";
i think the error is in the PHP file generating the user select it is missing the name attribute name="userSelect"
echo "<select id='userSelect' class='userSelect'>";
it should be
echo '<select id="userSelect" name="userSelect" class="userSelect">';
every form element with the name attribute gets posted with its value. if you do not enter the name attribute, the value can not be retrieved from the $_POST array. Also have in mind that disabled form inputs also do not get posted.
Edited the PHP quotes. Use Single qutes everyt time you do not need to insert PHP variable into the string. It is ~9 times faster than double quotes ;)

php drop down print selected item

I am trying to print the selected dropdwon item. I have already written the code for dropdown to fetch a column from database.
Now i should print the only the id of selcted dropdown item. i don't know how to make it. please help me, this is my code
<?
$query_name="SELECT id_cat,name FROM `fs01_metier_cat` ORDER BY `fs01_metier_cat`.`name` ASC";
$result = mysql_query ($query_name);
echo "<select name=category value=''></option>";
while($nt=mysql_fetch_array($result))
{
echo "<option value=$nt[name]>$nt[name]</option>";
}
echo "</select>";
$query_id="SELECT id_cat FROM `fs01_metier_cat`";
$result1 = mysql_query ($query_id);
while($row = mysql_fetch_assoc($result1))
{
echo $row['id_cat'];
}
?>
try this:
while($nt=mysql_fetch_array($result)){
echo "<option value='{$nt['id_cat']}'>{$nt['name']}</option>";
}
with {} php can insert also array values into a string and you should set ' ' around the attribute "value"'s value (alot of values here.. ^^), that the html is w3c conform (i dont know if a browser would take it as correct without them..)
without the { } it would look like that:
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['id_cat']."'>".$nt['name']."</option>";
}
depending on your editor code highlighting might work better in the second case ;)
and about the selected item:
i would suggest you to use jQuery to get the content of the selected item
var selectedId = $('#yourselectid option:selected').attr('value');
and then you can e.g. write it to the document or to a div:
document.write(selectedId);
or
$('#yourDivIdWhereYouWantToPutTheSelectedId').html(selectedId);
important: please note that i changed the value's index to id_cat because then you can handle the options with their id
Since the selected option changes everytime you change the dropdown selection, you can not handle this via php. There are ways to do that without a huge library like jQuery (since they are also just simple Javascript) but they simplify such things alot ;)

Is it possible to Query a Mysql database from a field selected from dropdown menu populated from a Query in php

Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)

how to retrieve checked values in php

I am a newbie in php. I have a form with multiple checkbox values. I wanna retrieve the checked values and diplay these values on other php form.
Below is the code which works perfectly fine if we add the checkboxes without while loop.
But when added through while loop I am not able to fetch the selected items.
xyzhtml.php(html form)
<?PHP
require ("DBConnect.php");
$selectQuery =mysql_query( "SELECT * FROM fruits where approved = 0");
while($row = mysql_fetch_array($selectQuery))
{
$fruit_name = $row['fruit_name'];
echo "<input type=\"checkbox\" name=\"things[]\" value=\"$fruit_name\">";
echo "<br>";
}
?>
On click of submit I call other php clled "xyz.php".
Below is the code used in it.
<?php
$checkBox = $_POST['things'];
echo $checkBox[0];
for($i=0; $i<sizeof($checkBox); $i++){
echo($checkBox[$i]);
}
?>
Please help.
Thanks in advance.
two things to check:
are you getting right values from the MySQL SELECT statement (check your HTML for empty checkboxes values and check your MySQL database for fruits that have approved field set to 0 to see if there are any)
when you don't tick a checkbox and submit the form, unticked checkboxes' values do not get submitted - have you thought about that?
Use foreach to record $_POST['things']
if (!empty($_POST['things'])) {
foreach ($_POST['things'] as $value) {
echo "the value are: ".$value;
}
}
Note: teh $_POST['things'] not $_POST['things[]']
I think your code should work, but it won't display anything if no checkboxes are selected.
I would however remove the explicit echo $checkbox[0] (unless this is for testing purposes).
Try a print_r($checkbox) to see what's actually in that array.

Categories