how to make drop down list item selected in database - php

I have a mysql table with about 40 items in it. What I want to do is reference those 40 items in a form on my webpage with a drop down list.
Instead of writing it out all 40 items like the following to know if an item has been selected:
<!doctype html>
<html>
</head>
<body>
<select>
<option value="Health & Beauty"<?php if (isset($_POST['SiteType']) && ($_POST['SiteType'] == 'Health & Beauty')) echo ' selected="selected"'; ?>>Health & Beauty</option></select>
</body>
</html>
and so on 40 times...
I am wondering how I could do it instead by using an SQL statement like the following:
here is what I have so far.
$sql = "SELECT * FROM sitetypes";
$f = mysqli_query($dbc, $sql) or trigger_error("Query: $sql\n<br />Mysqli Error: " . mysqli_error($dbc));
while($row2 = mysqli_fetch_array($f, MYSQLI_ASSOC)){
echo '<option value="' . $row2['SiteTypeID'] . '">' . $row2['SiteType'] . '</option><\select>';
}
The code above produces a nice drop down list, but I don't know how to make the database know when an item is selected by a user. What code do I write to make that happen? Can I use the SQL statement option or do I have to write each item out like I wrote at the beginning of this post.

This might help you
Add Select Attribute to your Table of type varchar
alter table user add Selected varchar(255)
Give them all values to '0'
and in html page
<select name="sitename">
<option></option>
<!-- your options -->
</select>
and when form is submitted by your you simply use this
echo $_POST['sitename'];
Then use this query to database know user selected this field in usertable or where you want
Update user set selcted='$_POST["sitename"]' where userid='currectuserid'

I hope I understood you right
$sql = "SELECT * FROM sitetypes";
$f = mysqli_query($dbc, $sql) or trigger_error("Query: $sql\n<br />Mysqli Error: " .mysqli_error($dbc));
while($row2 = mysqli_fetch_array($f, MYSQLI_ASSOC)){
echo '<option value="' . $row2['SiteTypeID'] . ' '.($row2['SiteTypeName'] == $_POST['SiteType'] ? 'selected="selected"':'').'">' . $row2['SiteType'] . '</option><\select>';
}
I'm not sure if the syntax is right, but you get the idea.
Edit: as I Can Haz Cheeseburger suggested u need to get the name from the db (not id) or pass the ID through POST

Related

Displaying form selected option results from database

Okay, I'm reframing this whole question because the earlier version was a bit convoluted.
Here's the scenario:
I have a MySQL table called "churches."
I have a form with four selects. The options are drawn dynamically from the table, so that users can search on four table columns to find churches that fit the criteria (country, state/province, city, presbytery)
I also have working code to get all the table data to display.
What I haven't figured out is how to use the selected option from the form to filter the results.
My current code is below:
<form action="display0506b.php" method="post">
<select name="country">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT country FROM churches");
$query_display = mysqli_query($link,"SELECT * FROM churches");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['country'] . "</option>";
}
?>
</select>
<select name="state">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT state FROM churches WHERE state != ''");
$query_display = mysqli_query($link,"SELECT * FROM churches WHERE state != ''");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['state'] . "</option>";
}
?>
</select>
<input type="submit" value="Go!">
</form>
<?php
if(isset($_POST['country']))
{
$name = $_POST['country'];
$fetch = "SELECT * FROM churches WHERE id = '".$name."'";
$result = mysqli_query($link,$fetch);
echo '<div class="churchdisplay">
<h4>' .$row['churchname'].'</h4>
<p class="detail">' .$row['detail'].'</p>
<p><b>' .$row['city'].'</b>, ' .$row['state'].' ' .$row['country'].'</p>
<p>' .$row['phone'].'</p>
// etc etc
</div>';
}
else{
echo "<p>Please enter a search query</p>";
}
?>
Note that in the form above, I only have two selects for illustration, but ultimately I will have four, as mentioned; and I am only attempting the country selection at this point to keep things simple. Ultimately, I will need the ability to select any (and preferably all) of the four categories.
As you can see, this code does attempt to "grab" the selected value from the form, but it's not working. I've pondered numerous tutorials and examples, but none of them do exactly what I'm after, and as an extreme PHP novice, I'm stumped.
So the question: how do I tweak this so that I can "grab" the form selection and display the relevant results from my table?
Edit: I am using mysqli syntax, and want to just use PHP and MYSQL (no Ajax etc) if possible.
Well, it looks like I've finally found what I needed here:
display result from dropdown menu only when value from it is selected
Or, I should say, I've got it to work with one select option. Still need to see if I can figure out how to get four working together.

Setting combo box to value dynamically retrieved from database in PHP

I have a task that I need to retrieve data from the database and set it in the Combo Box. Fortunately, I have done it.
Now, I have a Search Button which retrieves the data relevant in these text and combo boxes. My Issue is, After I click Search Button all my combo box and text box selected values become empty. How can I set those same data after clicking Search button ?
My Code Effort is,
<?php
$sql="select cat_id,cat_name from disease_category group by cat_id ";
foreach ($dbo->query($sql) as $row){
if(isset($_REQUEST['cat_name'])&&$_REQUEST['cat_name']==$row[cat_name])
{
echo "<option value=$row[cat_id] selected='selected' >$row[cat_name]</option>";
}
Else
{
echo "<option value=$row[cat_id]>$row[cat_name]</option>";
}
}
?>
My SEARCH button code,
<?php
include 'config.php';
if(isset($_REQUEST['SUBMIT']))
{
$cat=$_REQUEST['cat'];
$subcat=$REQUEST['subcat']
$sel=mysql_query("SELECT * from table_name where cat_id like '$cat%' AND sub_id like '$sub_cat%'AND survier like '$survier%' ")
}
It should be pretty simple. I still don't fully understand what you're trying to do. But if all you want is to dynamically populate an options list based on the results of a SQL query.
<?php
$sql = '
SELECT
*
FROM
`my_table`
';
$query = mysql_query($sql) OR die(mysql_error());
print '<select name="dropdown">';
while ($row = mysql_fetch_assoc($query)) {
print '<option value="'. $row['cat_id'] .'"';
if (
isset($_REQUEST['cat_name']) &&
$_REQUEST['cat_name'] == $row['cat_name']
) { print ' selected="selected"'; }
print '>'. $row['cat_name'] .'</option>';
}
print '</select>';
?>
You should be able to modify the SELECT query to fit your needs, and modify content within the while() loop, as well. That should get you going if I understand what you're trying to do.

PHP echo out data into HTML drop drop down menu

I have a HTML etc.. tags now what I want to achieve is upon a selection of ie. i want to load the related info from database to in a new tag with as many tags.
I am using PHP to do achieve this now at this point if for example i choose option1 then the query behind it retrieves relevant information and stores it in a array, and if I select option2 exactly the same is done.
The next step I made is to create a loop to display the results from array() but I am struggling to come up with the right solution to echo retrieved data into etc. As its not my strongest side.
Hope you understand what I am trying to achieve the below code will clear thing out.
HTML:
<select id="workshop" name="workshop" onchange="return test();">
<option value="">Please select a Workshop</option>
<option value="Forex">Forex</option>
<option value="BinaryOptions">Binary Options</option>
</select>
PHP:
$form = Array();
if(isset($_POST['workshop'])){
$form['workshop'] = $_POST['workshop'];
$form['forex'] = $_POST['Forex'];
$form['binary'] = $_POST['Binary'];
//Retrieve Binary Workshops
if($form['workshop'] == 'Forex'){
$sql2 = "SELECT id, course, location FROM courses WHERE course LIKE '%Forex%' OR course LIKE '&forex%'";
$query2 = mysqli_query($link, $sql2);
while($result2 = mysqli_fetch_assoc($query2)){
//The problem I am having is here :/
echo "<select id='Forex' name='Forex' style='display: none'>";
echo "<option value='oko'>.$result[1].</option>";
echo "</select>";
print_r($result2);echo '</br>';
}
}else{
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%Binary%' OR course LIKE '%binary%'";
$query = mysqli_query($link, $sql);
while($result = mysqli_fetch_assoc($query)){
print_r($result);echo '</br>';
}
}
}
Try this code:
$query2 = mysqli_query($link, $sql2);
echo "<select id='Forex' name='Forex' style='display: none'>";
while($result2 = mysqli_fetch_assoc($query2)){
echo "<option value='oko'>{$result['course']}</option>";
}
echo "</select>";
echo '</br>';
From the top in your php:
// not seeing uses of the $form I removed it from my answer
if(isset($_POST['workshop'])){
$workshop = $_POST['workshop'];
$lowerWorkshop = strtolower($workshop);
// neither of $_POST['Forex'] nor $_POST['Binary'] are defined in your POST. you could as well remove those lines?
//Retrieve Binary Workshops HERE we can define the sql in a single line:
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%$workshop%' OR course LIKE '&$lowerWorkhop%'";
$query = mysqli_query($link, $sql); // here no need to have two results
// Here lets build our select first, we'll echo it later.
$select = '<select id="$workshop" name="$workshop" style="display: none">';
while($result = mysqli_fetch_assoc($query)){
$select.= '<option value="' . $result['id'] . '">' . $result['course'] . '</option>';
// here I replaced the outer containing quotes around the html by single quotes.
// since you use _fetch_assoc the resulting array will have stroing keys.
// to retrieve them, you have to use quotes around the key, hence the change
}
$select.= '</select>';
}
echo $vSelect;
this will output a select containing one option for each row returned by either of the queries. by the way this particular exemple won't echo anything on screen (since your select display's set to none). but see the source code to retrieve the exemple.

select option to update second select option based on mysql populated dropdowns

I am trying to create a smart form which will automatically limit the options available of a second drop down box.
Background:
I am creating a ticketing system and I would like for the user to select a site from the "Site Selection" drop down and then the "User Selection" drop down will only contain users linked to the site selected on the first drop down, all information populated from MySQL.
Future:
I would then like to list all the services associated to that user with tick boxes under "Select Affected Services"
My js is pretty poor. So far I have been able to find some code by searching here that has allowed me to write the User's Computer ID into a text field. But I cannot figure out how to capture the output and query for the Computer Name (different table) and display that as a tick box option or to use the same method to limit the next lot of selection boxes. All code listed below I have not cleansed yet, alpha phase.
I realise that I could do this in steps using PHP only, but I am trying to pretty up my coding here and there.
Displaying Drop Downs:
<h3>Assign Site</h3>
<select id="site_add" name="site_add" style="width:217px; height:20px !important;">
<option value="-1"></option>';
$o = "SELECT * FROM company_sites WHERE company_id = " . $company_id . " ORDER BY sitename";
$rs = mysql_query($o);
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++) {
$r = mysql_fetch_array($rs);
echo '<option value="' . $r['id'] . '">' . $r['sitename'] . '</option>';
}
<h3>Assign User</h3>
<select id="comp_add" name="comp_add_1" style="width:217px; height:20px !important;">
<option value=""></option>';
$o = "SELECT * FROM company_staff WHERE company_id = " . $company_id . " ORDER BY id DESC";
$rs = mysql_query($o);
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++) {
$r = mysql_fetch_array($rs);
$user_computer_id = $r['computer_id'];
echo '<option value="' . $r['id'] . '">' . $r['firstname'] . ' ' . $r['lastname'] . '</option>';
}
Current JS to output selected user's computer ID into text field:
<script type="text/javascript">
window.onload=function() { attachBehaviors(); };
//
function attachBehaviors() {
document.getElementById(\'person\').onchange=function() {
loadUser(this.options[this.selectedIndex].value); // <-- check this, may be incorrect
}
}
function loadUser(optionvalue) {
// Always set a default
if (optionvalue==\'\') {
return;
}
opts = optionvalue.split(\':\');
var name = opts[0];
var email = opts[1];
document.getElementById(\'computer_id\').value=name;
}
</script>
<select name="person" id="person">
<option value=""></option>';
$result=mysql_query("SELECT * FROM company_staff");
while($row=mysql_fetch_array($result)) {
$submit_firstname = $row['firstname'];
$submit_lastname = $row['lastname'];
$submit_staff_id = $row['id'];
$submit_computer_id = $row['computer_id'];
echo '<option value="' . $submit_staff_id . '">' . $submit_firstname . ' ' . $submit_lastname . '</option>\n';
}
echo '
</select>
<input type="text" id="computer_id" name="name" placeholder="name" />
';
Any recommendations on how to achieve this would be greatly appreciated!
Thanks in advance!
You need AJAX, it's a combination of PHP and JS. ( javascript request data from the server, php processes the request, returns data ).
You would need to practice AJAX a bit to understand how to make this select box.
This is process in theory:
You output your first select box with PHP.
Make an onchange event handler for it that would call a server for information.
..options..
This updateNewDropDown function will take the value form a server response you selected and fetch the new data via PHP for the second select menu, and create the new select menu with the data AJAX response provided.
AJAX TUTORIALS:
http://api.jquery.com/jQuery.ajax/
http://www.w3schools.com/ajax/default.asp

get id from drop-down select tag to put into link

I have a drop-down select tag for Patients:
<select>
<?php
$qPatient = mysql_query("SELECT idpatients, firstName, mi, lastName, suffix FROM patients ORDER BY lastName ASC");
while($rowPatient = mysql_fetch_array( $qPatient )) {
if(isset($rowPatient['suffix']) && !empty($rowPatient['suffix'])){$suffix = " " . $rowPatient['suffix'];}else{$suffix = NULL;}
if(isset($rowPatient['mi']) && !empty($rowPatient['mi'])){$mi = " " . $rowPatient['mi'] . ".";}else{$mi = NULL;}
echo "<option value=" . $rowPatient['idpatients'] . $rowPatient . ">" . $rowPatient['lastName'] . $suffix . ", " . $rowPatient['firstName'] . $mi . "</option>";
}
?>
</select>
This generates a list of patients from the drop-down.
How do I get the patientID based on the selection from my drop-down to put to my link?
ex: Update
where $idpatients = the patient ID from the drop-down list select tag.
Also, I need to have 3 different links: 1.) update.php 2.) chart.php and 3.) report.php
Set this form method to GET. After submiting, value of select field will be shown as get variable. So, add name to your select:
<select name="parientId">
And proper action to your form:
<form action="update.php" method="GET">
And, of course submit button.
This is "static way" with form". If you are sure that you want to have link, not submit button, you can do it with jQuery:
$("#go").click(function(){ $("#idOfYourForm").submit(); }
...
Go !
Or catch .change() (sorry, not select()) on your <select...> and set $("#go").attr('href','update.php?patientId='+$("#yourSelectId").val());
P.S.
Get from SQL only fields you need, not *
Update
<form...>
<select name="patientId" id="patientSelect">
...
</select>
<a id="updatelink" href="">....</a>
<a id="deletelink" href="">....</a>
<script type="text/javascript">
$(document).ready(function(){
$("#patientSelect").change(function(){
$("#updatelink").attr('href',"update.php?id="+$("#parientSelect").val());
$("#deletelink").attr('href',"delete.php?id="+$("#parientSelect").val());
}
});
</script>
Something like that, written fast, not checked/tested

Categories