View Single Post
  #1 (permalink)  
Old 03-14-05, 09:11 AM
CutAndPaste's Avatar
CutAndPaste CutAndPaste is offline
Newbie Coder
 
Join Date: Mar 2005
Location: London, UK
Posts: 52
Thanks: 0
Thanked 0 Times in 0 Posts
Unhappy Use MySql field as source for form select field

I'm trying to get some code to populate a select field on a form with the contents of a field in a MySql database. I've got as far as the code below (with some help) BUT it only returns the first row in the table. Any ideas as to how I can get the full listing to display?

insert_items.php
Quote:
<?
error_reporting( E_ERROR | E_PARSE );

require_once( 'inc/config.inc.php' );
require_once( 'inc/mysql.class.php' );

//-------------------------------------

$oDb = new MySQL( $aCfg['db_host'], $aCfg['db_name'], $aCfg['db_user'], $aCfg['db_pass'] );

$sList = '';

if ( $oDb->Connect() )
{
$hQRes = $oDb->ExecQuery( "SELECT {$aCfg['db_field']} AS fld_alias FROM {$aCfg['db_table']} " );
if ( $aRes = $oDb->FetchArray($hQRes) )
{
$sTmp = addslashes( $aRes['fld_alias'] );
$sList .= "<option value='$sTmp'>$sTmp</option>\n";
}
echo $sList;
}
else
{
// print_r( $oDb->aErrors[count($oDb->aErrors)-1] );
}

?>
config.inc
Quote:
<?
// Configuration
$aCfg['db_host'] = 'localhost';
$aCfg['db_name'] = 'MyDatabase';
$aCfg['db_user'] = 'user';
$aCfg['db_pass'] = 'pwd';

$aCfg['db_table'] = 'MyTable';
$aCfg['db_field'] = 'MyField';

?>

mysql.class.php
Quote:
<?

class MySQL
{
var $sDBHost = '';
var $sDBName = '';
var $sDBUser = '';
var $sDBPass = '';
var $nPort = '';
var $hLink = '';
var $aErrors = array();

// Constructor
function MySQL( $sDBHost, $sDBName, $sDBUser, $sDBPass, $nPort = 3306 )
{
$this->sDBHost = $sDBHost;
$this->sDBName = $sDBName;
$this->sDBUser = $sDBUser;
$this->sDBPass = $sDBPass;
$this->nPort = $nPort;
}


function Connect()
{
$bResult = false;
$this->hLink = @mysql_connect( "{$this->sDBHost}:{$this->nPort}",
$this->sDBUser, $this->sDBPass );

if ( $this->hLink != false )
{
if ( @mysql_select_db( $this->sDBName, $this->hLink ) )
$bResult = true;
}
else
{
$this->aErrors[] = mysql_errno().':'.mysql_error();
}

return $bResult;
}

function Close()
{
@mysql_close( $this->hLink );
}

function ExecQuery( $sQuery )
{
$hResult = @mysql_query( $sQuery, $this->hLink );
return $hResult;
}

function FetchArray( $hQRes )
{
return @mysql_fetch_array( $hQRes );
}

function FetchRow( $hQRes )
{
return @mysql_fetch_row( $hQRes );
}

function NumRows( $hQRes )
{
return @mysql_num_rows( $hQRes );
}
}

?>
The Code is called from the form field like this:

Quote:
<select name="FieldName" id="FieldID" style="width:100%;">
<? include('insert_items.php'); ?>
</select>
Many thanks,

Simon
Reply With Quote