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
Related
I'm pretty new to Php and web development. What I'm trying to do here is besides fetching the value of selected id pck which is rate_perhour, I also want to fetch the value of option pack_id to POST on an insert file.
<?php
include ("dbconn.php");
$data = mysqli_query($db,"SELECT * FROM packages");
$cek = mysqli_num_rows($data);
$select= '<select id="pck" name="pck" class="form-control">';
$select.='<option value="">-- Select Package --</option>';
while($rs=mysqli_fetch_array($data,MYSQLI_ASSOC))
{
$select.='<option value="'.$rs['rate_perhour'].'">'.$rs['pack_id'].'</option>';
}
$select.='</select>';
echo '<input type="hidden" name="packid" id="packid">';
echo "<span class=style7>".$select."</span>";
?>
I'd tried the script to pass value into the hidden input to hold the id but didn't work as well.
<script>
$(document).ready(function()
{
$("#pck").change(function()
{
$("#packid").val(("#pck").find(":selected").text());
});
});
</script>
Parts of the POST method. It can get the Selected Value(pck) but not Option(packid)
<php
include ("dbconn.php");
if(isset($_POST['cuid']))
{
//Insert into 'reservation' table
$pack =$_POST['packid']; // Option
$rate =$_POST['pck']; // Selected Value
}
else
{
} ?>
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);
I have a similar problem like this one: Code Igniter - form_dropdown selecting correct value from the database, but in this case, i have 2 dropdown, State & City (using JavaScript). The dropdown option for City is repopulated based on what user choose in State dropdown.
For example, when a user choose a State (eg: New York), then the dropdown options for City become only cities in New York (eg: Albany, Amsterdam etc).
After user selects a value, then hits save, its saved to the database.
The problem is, how do i get the dropdown to automatically choose the one thats been selected by the user in the initial stage? I can do it if it's only 1 dropdown option. But in this case, the dropdown for City is repopulated based on what user choosed in State dropdown option.
Controller:
//this one i managed to get it automatically choose the one that's been selected by the user in the initial stage
$username=$this->session->userdata('username');
$data['orgtype'] = $this->m_user->get_orgtype_dropdown($username);
//these two are the problem
$data['state'] = $this->m_user->get_state_dropdown($username);
$data['city'] = $this->m_user->get_city_dropdown($username);
Model:
function get_orgtype_dropdown($username){
$sqlstr="SELECT * FROM a01 WHERE username='$username'";
$hslquery=$this->db->query($sqlstr);
foreach($hslquery->result_array() as $row){
$return[$row['orgtype']] = $row['orgtype'];
}
return $return;
}
function get_state_dropdown($username){
$sqlstr="SELECT * FROM a01 WHERE username='$username'";
$hslquery=$this->db->query($sqlstr);
foreach($hslquery->result_array() as $row){
$return[$row['state']] = $row['state'];
}
return $return;
}
function get_city_dropdown($username){
$sqlstr="SELECT * FROM a01 WHERE username='$username'";
$hslquery=$this->db->query($sqlstr);
foreach($hslquery->result_array() as $row){
$return[$row['city']] = $row['city'];
}
return $return;
}
View:
<?php
$orgtypeOption = array(
'Academic' => 'Academic',
'Professional' => 'Professional',
);
echo form_label("Organization Type : ");
echo form_dropdown('orgtype', $orgtypeOption, $orgtype);
echo br();
echo form_label("State : ");
?>
<select name ="state" id="countrySelect" size="1" onChange="makeSubmenu(this.value)">
<option></option>
<option value="USA" <?php if ($state=="USA") echo 'selected="selected"';?>>USA</option>
<option value="Singapore" <?php if ($state=="Singapore") echo 'selected="selected"';?>>Singapore</option>
<option value="Jawa Timur" <?php if ($state=="Jawa Timur") echo 'selected="selected"';?>>Jawa Timur</option>
<option value="Jawa Barat" <?php if ($state=="Jawa Barat") echo 'selected="selected"';?>>Jawa Barat</option>
</select>
<?php
echo br();
echo form_label("City : ");
?>
<select name="city" id="citySelect" size="1">
<option></option>
</select>
JavaScript:
var citiesByState = {
USA: ["NY","NJ"],
Singapore: ["taas","naas"],
"Jawa Timur": ["Surabaya","Malang"],
"Jawa Barat": ["Bandung","Banjar"]
};
function makeSubmenu(value) {
if(value.length==0) document.getElementById("citySelect").innerHTML = "<option></option>";
else {
var citiesOptions = "";
for(cityId in citiesByState[value]) {
citiesOptions+="<option>"+citiesByState[value][cityId]+"</option>";
}
document.getElementById("citySelect").innerHTML = citiesOptions;
}
}
function displaySelected() {
var country = document.getElementById("countrySelect").value;
var city = document.getElementById("citySelect").value;
alert(country+"\n"+city);
}
function resetSelection() {
document.getElementById("countrySelect").selectedIndex = 0;
document.getElementById("citySelect").selectedIndex = 0;
}
Here's the preview: application preview picture
Help please
I am still a beginner with PHP. I am having a problem with drop downs and links. I want to be able to choose an option in the drop down menu and it go to the specified page. For some reason only the links for the second drop down menu. (MUNICIPALITIES) will work correctly by linking to the specific municipality page. The crime drop down menu will not link to the specific crime page. I have included the code for the crime drop down and municipality drop down. I have also included the script below.
Ultimately my question is why aren't both drop downs functioning correctly with the link?
<script language="JavaScript" type="text/javascript">
function gopage(theLink) {
if (document.dropdown.theLink.value != "") {
location.href = document.dropdown.theLink.value;
}
}
</script>
<form name="dropdown">
<select name="theLink" onchange="gopage(theLink)">
<option value="ALL">Choose Crime associated with the Gang</option>
<?php
//echo 'NOWWWWWWWWWWWWWWWWWWWWWW';
if ($length3 <> 0) {
for ($m = 0; $m < $length3; $m++) {
$rows = $resultset3[$m][crime_name];
$trackchoices = $rows;
$options2 = "<option value=\"crimesmain.php?crime=$trackchoices\">$trackchoices</option>";
echo "$options2";
}
}
else if ($length3 == 0) {
$trackanswer = "NO CRIMES";
$options5 = "<option value=\"$trackanswer\">$trackanswer</option>";
echo "$options5";
}
?>
</select>
</form>
<br>
<br>
<form name="dropdown">
<select name="theLink" onchange="gopage(this)">
<option value="ALL">Choose Municipality associated with the Gang</option>
<?php
if ($length12 <> 0) {
for ($q = 0; $q < $length12; $q++) {
$rows2 = $resultset6[$q][municipality_name];
$trackchoices2 = $rows2;
//try
$options3 = "<option value=\"municipalitymain.php?mun=$trackchoices2\">$trackchoices2</option>";
//echo "<a href='municipalitymain.php?mun=$options3'>";
echo "$options3";
}
}
else if ($length12 == 0) {
$trackanswer = "NO MUNICIPALITY";
$options6 = "<option value=\"$trackanswer\">$trackanswer</option>";
echo "$options6";
}
?>
</select>
</form>
I think a better solution would be to pass the id of the select element to gopage so your function looks like this
function gopage(elId)
{
if (document.getElementById(elId).value != "") {
location.href = document.getElementById(elId).value;
}
}
First Dropdown
<select name="theLink" id="crime" onchange="gopage('crime')">
Second Dropdown
<select name="theLink2" id="muni" onchange="gopage('muni')">
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.