Does anyone know how to display MySQL db hierarchical data (Nested Set Model (http://www.phpro.org/tutorials/Managing-Hierarchical-Data-with-PHP-and-MySQL.html)) in a combo box as shown here under the "Category:" comboxbox field:http://dir.globetourism.biz/submit.php
Thanks
What you need to do is when you print your <option> tags for your combo box you have to check the depth (how to get the depth is in the article that's linked in your question) of each element and print that many "| " strings and another two underscores (__) to give it a nice tree-like look.
<?PHP
function GetCats($id='0',$sublev='0',$vname='C_Parent')
{
$DQ = new MySQLTable;
$DQ -> TblName = 'cat_categories';
$WHERE[$vname]['=']=$id;
$res = $DQ -> Select('C_ID,C_Name',$WHERE,'C_ID');
if (mysql_num_rows($res)>0)
{
while($row = mysql_fetch_assoc($res))
{
$ss='';
if($sublev!=='0')
{
for($i=0;$i<=$sublev*10;$i++)
{
$ss.=' ';
}
$ss.='|';
for($i=0;$i<=$sublev;$i++)
{
$ss.='-';
}
$ss.='>>';
}
$sel_s = '';
if(IsSet($_POST['C_Parent']))
{
if($row['C_ID']==$_POST['C_Parent'])
{
$sel_s = ' selected';
}
} elseif (IsSet($_POST['I_Parent'])) {
if($row['C_ID']==$_POST['I_Parent'])
{
$sel_s = ' selected';
}
} else {
$sel_s = '';
}
Echo "<option value=\"".$row['C_ID']."\" ".$sel_s.">".$ss.$row['C_Name']."</option>\r\n";
GetCats($row['C_ID'],$sublev+1);
}
}
}
Echo "<select name=\"C_Parent\">\r\n";
Echo "<option value=\"0\">...</option>\r\n";
GetCats();
Echo "</select>";
?>
Something like this.
But here was my own MySQL class. The query is: SELECT C_ID,C_Name WHERE C_Parent=$id ORDER BY C_ID where $id - php variable (current parent cat).
And there are $_POST variables if error submit to store selected.
This is not the most effective way to di it bcoz many queries. More effectively is to get all data to array to work with.
Related
I'm having issues databinding a dropdown list. I'm following a MVC structure and this is how I did it.
Here is a function from my Model layer:
function GetTillverkare()
{
$data = array();
mysql_set_charset('utf8');
$query = "Select Namn from Tillverkare";
if(!$sql = mysql_query($query)) {
throw new exception("Error: Can not execute the query.");
} else {
$num = mysql_num_rows($sql);
if($num>0)
{
for($i=0; $i<$num; $i++)
{
$data[$i] = mysql_fetch_array($sql);
}
}
}
return $data;
}
Here is the code from my Controller layer:
$displayResults = new Sok() //Sok is my model class.
$GetTillverkare = $displayResults->getTillverkare();
//I am able to print the $GetTillverkare so there is no problem with getting the data.
Here is my View layer
Fabrikat:<br /> <select name="Tillverkare_search" id="Tillverkare_search">
<option value="" selected="selected">Pick</option>
<option value="<?php echo $GetTillverkare ?>"</option>
</select><br/>
I don't get any error, but it doesn't display data o the dropdown list. It's empty
Your model function returns array so you can't print array by echo , if each index of array
is element of this list try to print this way
for($i=0;$<sizeof($GetTillverkere;$i++){
echo "<option value='".$GetTillverkere[$i]."'>".$GetTillverkere[$i]."</option>";
}
and you also have unclosed html tag in second option tag , and you try to print name to value of option but no in between tags which is the visible part of this tag
I am trying to extract multiple values from a row in a table in a mysql database. I want the selector to show the description only, and after the form is submitted, I want to be able to access additional information from that row. I am able to get all of the item_types out into an array, but I am not sure how to add the item_id. I don't want item_id to show up in the html selector.
I tried a few things like array_push. The only way I can think of getting this done is by making one big string in "value" and extracting the parts after the form is submitted.
Here is the function so far:
function createDropdown() {
echo '<select multiple name="items[]">';
try {
$items = mysql_query("SELECT item_id,item_type FROM items");
while ($row = mysql_fetch_assoc($items)) {
echo '<option value="'.$row['item_type'].'"';
echo '>'. $row['item_type'] . '</option>'."\n";
}
}
catch(PDOException $e) {
echo 'No results';
}
echo '</select>';
}
Hmm you can try to generate a lookup table whenever you create a drop-down list:
function createDropdown(&$ddlLookup) {
echo '<select multiple name="items[]">';
try {
$items = mysql_query("SELECT item_id,item_type FROM items");
while ($row = mysql_fetch_assoc($items)) {
echo '<option value="'.$row['item_type'].'"';
echo '>'. $row['item_type'] . '</option>'."\n";
$ddlLookup[$item_type] = $item_id;
}
}
catch(PDOException $e) {
echo 'No results';
}
echo '</select>';
}
Then whenever you need the id for a given description you use that table(array) to get it:
$mainDropdownLUT = array();
createDropdown($mainDropdownLUT);
var_dump($mainDropdownLUT['testCow']);
-> 734
Also, if you need to pass it to another page it can be serialized and added to a hidden field.
$mainDropdownLUT = serialize($mainDropdownLUT);
"<input type="hidden" value =\"$mainDropdownLUT\">"
-------------------------**OTHER PAGE **--------------
$mainDropdownLUT = unserialize($mainDropdownLUT);
Okay so I am developing a search engine for a non-profit group using MYSQL and PHP. The data appears fine from all the other fields. But when I try to get data from a drop down select box the data doesn't appear.
I know my code is pron to SQL injections however there isn't any important data kept on the server, it just info about treatments and research studies.
I would like to do it with a function. I was also wondering if there is anyway to retrieve data from multiple boxes. Like I have a keyword search and a drop down combo box both of them are set. How do I retrieve data from both columns in the database using the function I have? Thanks
Here is my code if you guys could help me that would be great thanks
The code for the html box
Broad Research Topic <select name="Treatment1">
<option value="Other">
Other
</option>
<option value="Treatment">
Treatment
</option>
<option value="PracticalCure">
Practical Cure
</option>
The php code to check if it is set
if (isset($_GET['Treatment1']) && in_array($_GET(['Treatment1']),
array('Treatment', 'PracticalCure', 'Other')) {
$state = $_GET['Treatment1'];
Investigator6($state); }
}
The Function Investigator6
function Investigator6($state)
{
$state = trim($state);
$state = preg_replace('/\s+/', ' ', $state);
//seperate multiple keywords into array space delimited
$keywords = explode(" ", $state);
//Clean empty arrays so they don't get every row as result
$keywords = array_diff($keywords, array(
""
));
//Set the MySQL query
if ($state == NULL or $state == '%') {
} else {
for ($i = 0; $i < count($keywords); $i++) {
$query = ("SELECT * FROM Studies1 WHERE BroadResearchTopic LIKE
' %$keywords[$i]%'");
}
//Store the results in a variable or die if query fails
$result = mysql_query($query) or die(mysql_error());
}
if ($state == NULL or $state == '%') {
} else {
//Count the rows retrived
$count = mysql_num_rows($result);
echo $count;
}
//If search variable is null do nothing, else print it.
if ($state == NULL) {
} else {
echo "You searched for <b><FONT COLOR=\"blue\">";
foreach ($keywords as $value) {
print "$value ";
}
echo "</font></b>";
}
echo "<p> </p><br />";
echo "</center>";
//If users doesn't enter anything into search box tell them to.
if ($state == NULL) {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.
b</font></b><br /></center>";
} elseif ($state == '%') {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.
</font></b><br /></center>";
//If no results are returned print it
} elseif ($count <= 0) {
echo "<center><b><FONT COLOR=\"red\">Your query returned no results from the
database.</font></b><br /></center>";
//ELSE print the data in a table
} else {
//Table header
echo "<center>";
echo "</center>";
//Colors for alternation of row color on results table
$color1 = "#d5d5d5";
$color2 = "#e5e5e5";
//While there are rows, print it.
while ($row = mysql_fetch_array($result)) {
//Row color alternates for each row
$row_color = ($row_count % 2) ? $color1 : $color2;
//table background color = row_color variable
echo "<td style = \"padding: 10px\">" . $row['BroadResearchTopic'] . "</td>";
$row_count++;
if ($state == NULL or $state == '%') {
} else {
//clear memory
mysql_free_result($result);
}
}
I have a dropdown control which and I would like it to default to a specific option based on the access of the logged in user. For example, the dropdown has 10 options but only administrators have access to view all 10 options. The majority of users only have access to 1 of the options though. The page contents are hidden/displayed based on whether or not the value of the dropdown is null.
Question: Using the example above, if an admin is logged in I need the dropdown to default to "Select an option". This way the page content is hidden. On the other hand, if a user with access to only 1 is logged in, I need it to default to that 1. This way they don't have to select anything and, by default the page content is displayed. How do I go about doing this?
Below is my current code which handles what the dropdown displays based on when a selection is made.
PHP/HTML
// Hide/Show main content div
<?php
if (isset($_GET['src'])) {
$src = $_GET['src'];
} else {
?>
<style>
#divmain { display: none; }
</style>
}
<?php } ?>
// Start of form, header, etc.
<select name="select1" id="select1">
<?php
$sql = getOptions();
$data = makeConnection($sql);
if ($src == null) { // If value is null, default to 'Select an option'
echo "<option selected value=\"\" disabled=\"disabled\">--Select an option--</option>";
while ($row = odbc_fetch_array($db)) {
echo "<option value=\"".$row['content']."\">".$row['content']."</option>";
}
} else { // If value not null keep the selected value selected
while ($row = odbc_fetch_array($db)) {
if ($row['content'] == $src) { $selected = " selected "; }
else { $selected = " "; }
echo "<option value=\"".$row['content']."\" ".$selected.">".$row['content']."</option>";
}
}
?>
</select>
JS
// Pass selected value on change
$('#select1').change(function() {
var sel = $(this).val();
location.href = "page1.php?src=" + sel;
}
SQL
// Hardcoding user for testing purposes, THIS WILL BE CHANGED
function getOptions() {
$results = "SELECT content, userid FROM table WHERE userid = 'username'";
return $results;
}
Any help is much appreciated and please let me know if I'm not clear about anything.
Got some help and have it figured out now. Here is the revised code:
PHP/HTML
// Hide/Show main content div
<?php
$src = null;
if (isset($_GET['src'])) {
$src = $_GET['src'];
} else {
?>
<style>
#divmain { display: none; }
</style>
}
<?php } ?>
// Start of form, header, etc.
<select name="select1" id="select1">
<?php
$sql = getOptions();
$data = makeConnection($sql);
if ($src == null) {
$i = 0;
$content = "";
while ($row = odbc_fetch_array($db)) {
$content .= "<option value=\"".$row['content']."\">".$row['content']."</option>";
$i++;
}
if ($i > 1) {
echo "<option selected value=\"\" disabled=\"disabled\">--Select an option--</option>";
}
echo $content;
if ($i > 1) { $oneopt = 1; }
else { $oneopt = 0; }
} else {
while ($row = odbc_fetch_array($db)) {
if ($row['content'] == $src) { $selected = " selected "; }
else { $selected = " "; }
echo "<option value=\"".$row['content']."\" ".$selected.">".$row['content']."</option>";
}
}
?>
</select>
JS
$('#select1').change(function() {
var sel = $(this).val();
location.href = "page1.php?src=" + sel;
}
<?php
global $optone;
if ($optone == 1) {
echo "$('#select1').trigger('change');";
}
?>
SQL -- Stays the same
#chenasraf really appreciate the help! Hope this can be of some help to someone in the future!
The preselected option is always the first to have a "selected" attribute. Your first disabled one has it first on all cases, so it's always chosen. Remove that and work from there.
On a side note, I think you can manage to make this options part work better. I've taken the liberty of rewriting it for you:
<select name="select1" id="select1">
<?php
$selected = '';
while ($row = obdc_fetch_array($db)) {
$options[] = '<option value="'.$row['content'].'">'.$row['content'].'</option>';
if ($row['content'] == $src)
$selected = count($options) - 1;
}
array_unshift($options, '<option disabled="disabled"', $selected == '' ? ' selected="selected"' : '','>--Select an option--</option>');
foreach ($options as $option) {
echo $option;
}
?>
</select>
I'm using a form where the user can edit an entry. Everything is populating and all is well with the exception that I can't get the drop down to show the project that they've already assigned the image to.
$project_qry = "SELECT * from projects ORDER BY title ASC";
$project_res = mysql_query($project_qry);
$project_drop = "<select name=\"project_id\">\n";
while ($row = mysql_fetch_array($project_res))
{
if ($project_id == $row[title])
{
$project_drop .= "<option value=\"$row[id]\" selected>$row[title]</option>\n";
}
else
{
$project_drop .= "<option value=\"$row[id]\">$row[title]</option>\n";
}
}
$project_drop .= "</select>\n";
I'm sure it's something devilishly simple but I'm stumped.
{
if ($project_id == $row[id])
{
$project_drop .= "<option value=\"$row[id]\" selected=\"selected\">$row[title]</option>\n";
}
else
{
$project_drop .= "<option value=\"$row[id]\">$row[title]</option>\n";
}
}
You need to compare the value and not the title. It is the value that gets posted ($_POST)
selected="selected" makes it XHTML compliant.
bigstylee answered correctly. I also recommend to separate the values of the array and your string:
$project_drop .= "<option value='". $row['id'] ."'>".$row['title']."</option>";
Also drop \n. Outputting \n won't generate a line break in the browser. And it is unnecessary.