How to populate Dropdown values from database in php [duplicate] - php

This question already has answers here:
Using PHP to populate a <select></select> dropdown? [duplicate]
(7 answers)
Closed 7 months ago.
Hello Friends how to get data from database in Drop-down list?
This is my code but i can't get data in Drop-down list,
This is my php code.
public function System_parameter_dropdown_value() {
$sql= " SELECT * FROM SYSTEM_PARAMETERS WHERE PARAMETER_KEY='ROLE_TYPE'";
$rs= mysql_query($sql) or die(mysql_error());
$option_list="<option value=0>Select Role Type</option>";
while($data= mysql_fetch_assoc($rs)) {
$option_list.="<option value='$data[PARAMETER_KEY]'>
$data[PARAMETER_VALUE]</option>";
}
return $option_list;
}
This is my html option list, When i run the code it's show nothing in Dropdown list
<label class="control-label" for="roleid" style="padding-right: 80px;">ROLE TYPE</label>
<select id="" name="roleid">
<?php echo $option_list['PARAMETER_KEY']['PARAMETER_VALUE'];?>
</select>
I am Stuck on this code , please Guide me How to Resolve it.

Try some thing like this:
$arr = array(1 => 'MP', 2 => 'UP');
echo '<select>';
foreach($arr as $key => $val)
{
echo '<option value="'.$key.'">'.$val.'</option>';
}
echo '</select>';
It will generate html like:
<select>
<option value="1">MP</option>
<option value="2">UP</option>
</select>
In your case it is like:
<select id="" name="roleid">
<?php echo System_parameter_dropdown_value();?>
</select>

that's because $option_list in not array but string:
<?php $option_list = $your_object->System_parameter_dropdown_value(); ?>
<label class="control-label" for="roleid" style="padding-right: 80px;">ROLE TYPE</label>
<select id="" name="roleid">
<?php echo $option_list;?>
</select>
Method should be changed too
public function System_parameter_dropdown_value()
{
$sql= " SELECT * FROM SYSTEM_PARAMETERS WHERE PARAMETER_KEY='ROLE_TYPE'";
$rs= mysql_query($sql) or die(mysql_error());
$option_list="<option value=0>Select Role Type</option>";
while($data= mysql_fetch_assoc($rs))
{
$option_list.=sprintf("<option value='%s'>%s</option>", $data['PARAMETER_KEY'], $data['PARAMETER_VALUE']);
}
return $option_list;
}

If you are writing the function System_parameter_dropdown_value inside a class, you have to create an object of the class and then call the function.
Like this
$classObj = new className();
echo $classObj->System_parameter_dropdown_value();
class className {
public function System_parameter_dropdown_value() {
$sql= " SELECT * FROM SYSTEM_PARAMETERS WHERE PARAMETER_KEY='ROLE_TYPE'";
$rs= mysql_query($sql) or die(mysql_error());
$option_list="<option value=0>Select Role Type</option>";
while($data= mysql_fetch_assoc($rs)) {
$option_list.="<option value='$data[PARAMETER_KEY]'>
$data[PARAMETER_VALUE]</option>";
}
return $option_list;
}
}
I think this might help you.

I hope this one helps, it's complete example with the db connection.
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT record FROM table";
$result = mysql_query($sql);
echo "<select name='tagName'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['tagName'] ."'>" . $row['tagName'] .</option>";
}
echo "</select>";

Related

Populating a Dropdown Selection from MySql & Php [duplicate]

This question already has answers here:
Using PHP to populate a <select></select> dropdown? [duplicate]
(7 answers)
Closed 7 months ago.
Hopefully this question doesn't drive anyone to drink.
I've been at this for about 9 hours now and cannot get a drop down to populate. I know I'm missing something very simple and I'm reaching out to see if anyone can give me some insight. The table I'm calling from has 1 column and just has names (which are unique)
I have a db class being called in the beginning of all of my pages, in all but 2 cases , its working fine, in the 2 exceptions, it's the pages that require the dropdown. I've deleted and recreated both pages with no change.
Both Pages are named select.php and select_p.php. The initial call is as follows and breaks at the first "->" so begins printing everything after it and up until the "?>"
include("database.class.php");
$database = new database;
$sql_page = $database->mysqlQuery("SELECT * FROM spec_tables");
$edata_page = $database->mysqlFetchArray($sql_page);
return $edata_page;
?>
Heres the fucntion in the class file that works on 2 other sites and other pages in this same site
function mysqlQuery($qry)
{
$rs = mysql_query($qry, $this->DatabaseLink);
return $rs;
echo mysql_error();
}
Now if I use the code in the page, it doesnt print but the dropdown is blank
<select name='list' value=''><option>Select List</option>
<?
$sql_page = $database->mysqlQuery("SELECT * FROM spec_tables");
$edata_page = $database->mysqlFetchArray($sql_page);
return $edata_page;
foreach($edata_page as $row){
?>
<option value="<?php echo $row; ?>"><?php echo $row; ?></option>
<? } ?>
</select>
I've looked at the following (plus about 20 pages that are not this close)
PHP- Fetch from database and store in drop down menu html
How to put table value in a dropdown menu with MYSQL and PHP
http://www.plus2net.com/php_tutorial/list-table.php
http://www.tutorialrepublic.com/faq/how-to-populate-dropdown-list-with-array-values-in-php.php
Here's all the snippets of code I've tried to no avail, some of them actually print the code in the html form, any constructive help would be very much appreciated.
*********************************************************
<select name='list' value=''><option>Select List</option>
<?
$sql_page = $database->mysqlQuery("SELECT * FROM spec_tables");
$edata_page = $database->mysqlFetchArray($sql_page);
return $edata_page;
foreach($edata_page as $row){
?>
<option value="<?php echo $row; ?>"><?php echo $row; ?></option>
<? } ?>
</select>
*****************************************************************
<select name='list' value=''><option>Select List</option>
<?
$result = $database->mysqlQuery("select * from spec_tables");
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$row = array();
for ($i = 0; $i < $num_fields; $i++)
while ($row = mysql_fetch_row($result))
{
?>
<option value="<?php echo $row; ?>"><?php echo $row; ?></option>
<? } ?>
</select>
********************************************************************
<select name='list' value=''><option>Select List</option>
<?
$result = $database->mysqlQuery("select * from spec_tables");
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo '<option value=". $row['name'] .">' . $row['name'] . '</option>';
}
}
?>
</select>
****************************************************************************
Placed in top of file
$servername = "localhost";
$username = "uname";
$password = "pword";
$dbname = "db_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if ($result = mysqli->query("SELECT * FROM 'spec_tables'")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
**********************************************************************
<?
$sql = "select * from spec_tables";
$result = mysql_query($sql);
echo "<select name='list' value=''><option>Select List</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] ."'>" . $row['name'] ."</option>";
}
echo "</select>";
?>
**************************************************
Heres the code thats working
//placed in beginning of code
<?php
include("database.class.php");
$database = new Database;
$result = $database->mysqlQuery("SELECT * FROM spec_tables");
?>
//Placed inside html form
<?php
echo '<select name="list">';
echo '<option>Select List</option>';
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['name'] .'">' . $row['name'] .'</option>';
}
echo '</select>';
?>

How to keep the selected value from a multiple select form with PHP?

I have an issue with this form. I need to keep the values selected and I don't find the way. The thread where I posted the first time: Create php fom select multiple taking values from a table bd
The form:
<select name="fan[]" multiple="multiple"> <!-- Aquí se llama a la función verificarListaMultiple -->
<?php
foreach ($deportes as $aficion) {
echo "<option value='".$aficion['idD']."'";
if (isset($fan)) {
verificarListaMultiple($aficion,$fan);
}
echo " >{$aficion['nombreDep']}</option>\n";
}
?>
</select>
And the function I'm trying to use:
function verificarListaMultiple($array, $valor) {
if (in_array($valor, $array)) {
echo 'selected = "selected"';
}
}
Thanks.
Ok, i resolved on this way:
Form insert-data
<?php
foreach ($deportes as $deporte)
{
echo "<option value='".$deporte['idD']."'";
if (isset($depo)) verificarListaMultiple($depo, $deporte['idD']);
echo " >{$deporte['nombreDep']}</option>\n";
}
?>
Then, the values are inserted in a table bd:
<?php
if (isset($_POST['fan']))
{
$idPersona = mysqli_insert_id($conexion);
foreach ($depo as $sport) {
$sport = mysqli_real_escape_string($conexion, $sport);
$sql = "INSERT INTO mec(id,idD) VALUES ('$idPersona','$sport') ";
$resul = mysqli_query($conexion, $sql);
}
And finally i would like to edit the form edit_Data. The values showed, must be the values inserted in form edit_Data, and must be keep selected:
Form edit-data:
<?php
foreach ($deportes as $deporte)
{
echo "<option value='".$deporte['idD']."'";
if (isset($depo)) verificarListaMultiple($depo, $deporte['idD']);
echo " >{$deporte['nombreDep']}</option>\n";
}
?>

How to create select option from database?

I'm working on a form that has 4 different select elements from 2 tables of a database. I haven't done anything like this and I don't really know how to do it.
I have a table called "students" from I need "name" and "class" and a table called "books" from I need "writer" "title" ... all is one select element and all has more than 2 option values.
I've tried with only one sql query and one select but it shows only one option on the site, wether it has about 6 values in the database.
My code:
$sql = "SELECT class
FROM students";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$select_class = "<option value={$row['class']}>{$row['class']}</option>";
}
<select id="class" name="class">
<?php print $select_class; ?>
</select>
How would it be correct?
try this
$sql = "SELECT class FROM students";
$result = mysql_query($sql);
echo '<select id="class" name="class">';
while ($row = mysql_fetch_assoc($result)) {
echo "<option value={$row['class']}>{$row['class']}</option>";
}
echo '</select>';
You are overwriting $select_class on each while() loop. You need to concatenate $select_class . Change to $select_class .=
$select_class = "";
while ($row = mysql_fetch_assoc($result)) {
$select_class .= "<option value={$row['class']}>{$row['class']}</option>";
}
Changing this:
$select_class = "<option value={$row['class']}>{$row['class']}</option>";
to this:
$select_class .= "<option value={$row['class']}>{$row['class']}</option>";
might solve your problem.
Right now you are constantly resetting the value of $select_class, instead of adding to it. The .= assignment should help you get around this.
As always, be sure to up-vote any StackOverflow answers you find useful.
Try this
<?php
$dbhandle = mysql_connect($hostname, $username, $password) or die("can't connect");
$table = "students";
$sql = "SELECT * FROM students";
$result = mysql_query($sql, $dbhandle);
mysql_data_seek($result, 0);
?>
<form>
<select class="dropdown" name="dropdown">
<?php
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['class'] . '">' . $row['class'] . '</option>';
}
}
?>
</select>
</form>

Edit drop down but not showing selected value from mysql data base in php

I am new to php, i created drop down which calling data from mysql data base, user selects option and its save to data base.
Problem Arises in edit form in which its do not showing selected value.
Drop Down code is below:
$query = 'SELECT name FROM owner';
$result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
//create selection list
echo "<select name='owner'>\name";
while($row = mysql_fetch_row($result))
{
$heading = $row[0];
echo "<option value='$heading'>$heading\n";
}
echo "</select>"
Please advise solution for the edit form.
Thanks in Advance
you must close <option> tag:
echo "<option value='$heading'>$heading</option>";
$query = 'SELECT name FROM owner';
$result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
//create selection list
echo "<select name='owner'>\name";
while($row = mysql_fetch_row($result))
{
$heading = $row[0];
?>
<option <?php if($heading=="SOMETHING") { echo "selected='selected'"; } ?> value="SOMETHING">SOMETHING</option>
<option <?php if($heading=="SOMETHING2") { echo "selected='selected'"; } ?> value="SOMETHING2">SOMETHING2</option>
<option <?php if($heading=="SOMETHING3") { echo "selected='selected'"; } ?> value="SOMETHING3">SOMETHING3</option>
<?php
}
echo "</select>"
I'd do it this way.
$numrows = mysql_num_rows($result);
if ($numrows != 0){
echo "<select name='owner'>\name";
while ($x = mysql_fetch_assoc($result)){
echo "<option value='".$x['heading']."'>".$x['heading']."</option>";
}
echo "</select>";
}
$x['heading'] is using the value of the row 'heading' in the database
It's much more efficient and simply looks more sophisticated.

php - auto select drop down menu based on parameters in browser link

If in the browser I have parameters like:
http://localhost/specials.php?year=2009&make=honda&model=civic
and the dropdown looks something like this:
<select name="year">
<?php
$query = mysql_query("select distinct year from tbl_content where year = '$year'");
while($row = mysql_fetch_assoc($query)) {
echo "<option value=\"{$row['year']}\">{$row['year']}</option>";
}
?>
</select>
Now what I'm trying to do is show select when the dropdown options value is equal to the parameter year in the browser URL.
I tried this:
<select name="year">
<?php
$query = mysql_query("select * from tbl_year
while($row = mysql_fetch_assoc($query)) {
#=============================
if(isset($_GET['year'])) {
$year = (int)$_GET['year'];
if($year == $row['year'] { $selected = "selected"; }
else { $selected = "";
}
echo "<option value=\"{$row['year']}\" {$selected}>{$row['year']}</option>";
}
?>
</select>
Maybe try "selected='selected'" to make it valid xml.
<select name="year">
<?php
$selectedYear = NULL;
if(isset($_GET['year']))
$selectedYear = (int)$_GET['year'];
$query = mysql_query('SELECT year FROM tbl_year GROUP BY year ORDER BY year ASC');
while($row = mysql_fetch_assoc($query)) {
echo '<option value="' . htmlspecialchars($row['year']) . '"';
if($selectedYear === (int)$row['year']) {
echo ' selected="selected"';
}
echo '>' . htmlspecialchars($row['year']) . '</option>";
}
?>
</select>
Fell free to separate functionality!
<?php
function selectList($name,$values,$labels=null,$selected=null){
if($labels==null) $labels=&$values;
$data="<select name='$name'>";
foreach($values as $k=>$v){
$selected=($v==$selected)?'selected="selected"':false;
$data.="<option value='$v' $selected>".htmlspecialchars($labels[$k])."</option>";
}
$data.="</select>";
return $data;
}
$select=isset($_REQUEST['year'])?(int) $_REQUEST['year']:null;
$query=mysql_query("SELECT DISTINCT `year` FROM `tbl_year` ORDER BY `year`");
while(($row=mysql_fetch_assoc($query))!==false){
$values[]=$row['year'];
}
echo selectList("year",$values,null,$select);
?>

Categories