Jump to content

Using PHP to dynamically generate a select tag from MySQL Entry


alan_k

Recommended Posts

Hello,

New to PHP and am stuck on one aspect.I have a simple equipment tracking form and in my edit table page I fill in the existing text values using `value="<?php echo $svc_tag;` for example. I have recently added a select tag but am stuck on how I can have the select box have the current value I am retrieving from MySQL chosen in the select box. Thru research I see the value attribute is not applicable here. Does anyone know of a way for me to have the select box populated with the current value from MySQL. I'm thinking along the lines I need some PHP code to generate the select tag code on the fly. My select statement statement on the add table entry page is this: Equipment Status:<select name="ud_Borrwd_Rsn" <option value="Borrowed" selected="selected">Borrowed</option> <option value="Repair">Repair</option> <option value="Replacement" >Replacement</option> <option value="Other">Other</option> </select><br />

Link to comment
Share on other sites

confused about what u expected exactly but I think mean the following.....

<select name="ud_Borrwd_Rsn">    <option><?php echo $row['ud_Borrwd_Rsn']; ?></option>    <option>Borrowed</option>    <option>Repair</option>    <option>Replacement</option>    <option>Other</option></select>

and yes u don't have value inside option tag. what u use inside opening and closing of option is itself a value..

Link to comment
Share on other sites

I'm not sure which MySQL library you're using, but you can generate options with a loop in any case, the syntax will be sligntly different depending on the case. It will look something similar to this:

<select name="ud:Borrwd_Rsn"><?phpwhile([assign a result to a variable $row]) {    echo "<option value='{$row['value']}'>{$row['name']}</option>";}?></select>
Link to comment
Share on other sites

I'm sorry I should have been more specific. Here is the PHP I'm using:

Equipment Status:<?php    $option_to_preselect = $rsn_brwd;echo $option_to_preselect;$options = array(    1 => 'Borrowed',    2 => 'In for Repair',    3 => 'Replacement',    4 => 'Returned',    5 => 'Other');print '<select name="Borrwd_Rsn_val" id="input_select">';foreach ($options as $index => $value){    print '    <option value="' . $index . '"';        if ($index == $option_to_preselect)    {        print ' selected ';    }        print '>' . $value . '</option>';}print '</select>';?>

This generates the select tag fine but again the default selected option is being generated by the php not the choice in the drop list being stored in MySQL. I dont want users to have to reselect the objects

drop down value I want it prechoosen so if that is not what they want to modify they can leave the field alone. Like I said I am new to php so if anyone has a more elegant solution please advise. ThanksP.S.- Using MySQL 5.5 on a LAMP server running Ubuntu 14.4

Edited by alan_k
Link to comment
Share on other sites

Can you write a query that retrieves information from the database? Without knowing your table structure and which MySQL library you're using I can't show you the right way to do it.

 

I think you might have missed my previous post as well.

Link to comment
Share on other sites

Here is link to my code for page on Pastebin: http://pastebin.com/QhAccb1k

And here is the MySQL export file:

 

-- phpMyAdmin SQL Dump-- version 4.0.10deb1-- http://www.phpmyadmin.net---- Host: localhost-- Generation Time: Sep 22, 2014 at 01:46 PM-- Server version: 5.5.38-0ubuntu0.14.04.1-- PHP Version: 5.5.9-1ubuntu4.4SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";SET time_zone = "+00:00";/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;/*!40101 SET NAMES utf8 */;---- Database: `inventory_form`---- ------------------------------------------------------------ Table structure for table `Inventory`--CREATE TABLE IF NOT EXISTS `Inventory` ( `FName` varchar(12) NOT NULL, `LName` varchar(15) NOT NULL, `Eqpmnt_Brwd` varchar(25) NOT NULL, `Service_Tag` text NOT NULL, `Brwd_Rsn` varchar(15) NOT NULL, `Date_Taken` date NOT NULL, `Exp_Return` date NOT NULL DEFAULT '2014-09-01', `Comments` varchar(150) NOT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2105 ;---- Dumping data for table `Inventory`--INSERT INTO `Inventory` (`FName`, `LName`, `Eqpmnt_Brwd`, `Service_Tag`, `Brwd_Rsn`, `Date_Taken`, `Exp_Return`, `Comments`, `id`) VALUES('aasass', 'sddssddss', 'Laptop', '455444', 'Returned', '2014-09-20', '2014-10-05', 'Testing', 2101);/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

I also notice that when I modify the drop list value on the modify page it is not being written to MySQL.

Link to comment
Share on other sites

OK, from this code, I think what you're trying to ask is to have the dropdown preselected based on information from the database.

 

That's simple:

if ($rsn_brwd == $index) {    print ' selected ';}

If that's not what you're asking, then I'm not sure. You don't seem to have a database table exclusively for the dropdown list values.

 

On a side note, you don't need a while() loop if you're only retrieving one record from the database, and you should be prepared for the possibility that the record doesn't exist.

if($row = $result->fetch()) { // The row was found    $first=$row['FName'];    $last=$row['LName'];    $eqpmnt_brwd=$row['Eqpmnt_Brwd'];    $svc_tag=$row['Service_Tag'];    $rsn_brwd=$row['Brwd_Rsn'];    $date_brwd=$row['Date_Taken'];    $ret_date=$row['Exp_Return'];    $comments=$row['Comments'];    // The rest of the page information should actually be here} else {    // Show a message telling the user that no content was found for this ID}
Link to comment
Share on other sites

Yes I am using PDO. And I am storing the values for the drop down list in an array in the page not a seperate database table. The logic is to compare the values in the array with retrieved database value (which is the current drop down selection) and construct the select tag using php. At least that is how it should work on paper. Unfortunately I always get the default value and when I try to update via _POST the value is not getting updated. Once again see my link above for full code of the page....

Link to comment
Share on other sites

Here is the code that I got it to work with:

Equipment Status:<?php    $option_to_preselect = $rsn_brwd;$ddown_options = array(    'Borrowed',    'In for Repair',    'Replacement',    'Returned',    'Other');$arrlength=count($ddown_options);print '<select name="ud_Borrwd_Rsn" id="input_select">';for ($x=0;$x<$arrlength;$x++){           if ($ddown_options[$x] == $option_to_preselect)    {        print '    <option value="' . $ddown_options[$x] . '"' . ' selected="selected">' . $ddown_options[$x] . '</option>';    }        else {            print '    <option value="' . $ddown_options[$x] . '">' . $ddown_options[$x] . '</option>';          }}print '</select>';?>

Thanks to everyone for their input. The only small thing I have to complain about if you view the source code the select statement prints out as such :

<select name="ud_Borrwd_Rsn" id="input_select"> <option value="Borrowed">Borrowed</option> <option value="In for Repair">In for Repair</option> <option value="Replacement">Replacement</option> <option value="Returned">Returned</option> <option value="Other">Other</option>

all in one line. Just from a readability standpoint is there anyway to have the source code print on seperate line like it does when I use the select statement with pure html and indents and line breaks are preserved in source code. Also do you think it even warrants any error checking because it is a drop down list and always has a predefined value stored in it. Great forum I'm sure I will be returning. How do I mark thread as solved.

Edited by alan_k
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...