Something I have created for a project recently (note that I use my own db
wrapper functions - just substitute the dbconn(), dbquery(), dbnumrows() and
dbresult() for your database functions - e.g. mysql_connect() for mysql,
ms_sql_connect() - look them up in the PHP manual however as I am not sure
that those are completely right).

This code works quite well but the current value will be repeated (it will
be selected but it can also be found in the drop down -- fixes anyone?) and
I have tested it quite throughly (although I can't swear its bug proof as
this has only got to alpha stage in my current project).  If you want
further explanation of the code / an example then let me know and I will dig
something out for you.

$id = the field name that the id value resides in the table
$name = the name field in the table,
$table is the name of the SQL table
$current is optional (hence is set by default to NULL)
and htmlelname refers to the HTML class name that the dropdown will be
given.

<?php
// create a drop down HTML form element from the fields and table specified
function dropdownfromdb($id, $name, $table, $current = NULL, $htmlelname =
"select") {
$sqlquery= "SELECT $id, $name FROM $table";
$db = dbconn();
$res = dbquery($sqlquery, $db);
$j = dbnumrows($res);
    if($j > 0) {
     print "<select name=\"$htmlelname\">\n";
        for ($i = 0; $i < $j; $i++) {
            $val = dbresult($res, $i, 0);
            print "<option ";
                if ($current == $val) print "selected ";
            print "value =\"$val\">\n";
            print dbresult($res, $i, 1)."</option>\n";
        }
        print "</select>\n";
    }
else print "ERROR dropdownfromdb function failed";
}
?>

Hope that helps, sorry if this email is a bit scrappy, very tired!

Ollie

P.S. Does anyone know of a better way than DIE() (or my above error message)
to capture errors - eg Java / C++'s exceptions?  I couldn't find any mention
of exceptions in the PHP manual.


-----Original Message-----
From: B.J.Rumsey [mailto:[EMAIL PROTECTED]]
Sent: 30 January 2002 06:30
To: php-db
Subject: drop down list


I have two fields artist_id, artist.  How do I put the contents of "artist"
into a dropdown list.




-- 
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]

Reply via email to