简体   繁体   English

从Joomla中的MySQL数据库填充PHP下拉列表

[英]Populate a PHP Dropdown List from MySQL Database in Joomla

I am a very inexpert php programmer, I ve done some asp.net programming but never php. 我是一个非常不熟练的php程序员,我做了一些asp.net编程,但是从来没有php。

I need the requirement to add a dropdownlist with values from a table in the mysql database. 我需要添加一个下拉列表,其中包含来自mysql数据库中表的值。 I manually created a table training: id training date hour openseats 我手动创建了一个表格训练:id训练日期小时openseats

And I need to display this dates and hour in the dropdownlist, so once the user clikc submits this get stored into a table called jos_jquarks_users_acknowledge 而且我需要在下拉列表中显示此日期和小时,因此一旦用户clikc提交了该日期和时间,就将其存储到名为jos_jquarks_users_acknowledge的表中

Can you help me how to pupulate the dropdown? 您能帮我如何简化下拉菜单吗?

Code: 码:

{source}
<!-- You can place html anywhere within the source tags -->
<?php 
// If the constant _JEXEC is not defined, quit now.
// This stops this script from running outside of the system.
defined( '_JEXEC' ) or die( 'Restricted access' );
?>

<?php

$user = JFactory::getUser(); 
$id = $user->get('id'); 
$name = $user->get('name');
$username = $user->get('username'); 
$department = $user->get('department');

$vardate = date("Y-m-d H:i:s");

$acknowledge = 1;
$courseTitle = $mainframe->getPageTitle();

$courseDate = ;
$courseHour =;


/***************************************/

$db = &JFactory::getDBO();

$query = "
INSERT INTO
`jos_jquarks_users_acknowledge`
(
course_name,
user_id,
employeeNumber,
department,
name,
acknowledge,
timeStamp,courseDate,
courseHour
)
VALUES
(
'{$courseTitle}',
'{$id}',
'{$username}',
'{$department}',
'{$name}',
'{$acknowledge}',
'{$vardate}',
'{$courseDate}',
'{courseHour}'

 )";

$db->setQuery($query);

$db->query();


if($db->getErrorNum()) { 
JError::raiseError( 500, $db->stderr()); 
}

?>

<form name="quiz_info" method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"> 

<?php echo JText::_('Do you want to enroll into the course?') ; ?>

<? $queryCourses="SELECT training_id,training,trainingDate FROM training"; ?>

$result = mysql_query ($queryCourses); 
echo "<select name=courseDates value=''>Date</option>"; 
// printing the list box select command 

while($nt=mysql_fetch_array($result)){//Array or records stored in $nt 
echo "<option value=$nt[id]>$nt[training]</option>"; 
/* Option values are added by looping through the array */ 
} 
echo "</select>";//Closing of list box

<input id="proceedButton" name="proceedButton" value="Acknowledge" type="submit" />

<input type="hidden" name="layout" value="default" /> <?php echo JHTML::_( 'form.token' ); ?>

</form>

{/source} 

COMPONENT CONTROLLER/TASK FUNCTION: 组件控制器/任务功能:

public  function ShowData()        {
    $course_id = JRequest::getVar('id');

    $db = JFactory::getDBO();
                $query = $db->getQuery(true);
                $query->select('*');
                $query->from('#__tablename');
                $query->where('courseid =\'' . $course_id.'\'');
                $db->setQuery((string)$query);

$data=$db->loadObjectList();

    $option = '<option value="0">choose...</option>';
     foreach ( $data  as $row)  {

     $option .= '<option value="' . $row->candidateid . '">' . $row->firstname .' '. $row->lastname. '</option>';

    }
    echo json_encode(array('options' =>$option));
jexit(); 

 }

ajax: 阿贾克斯:

Searching from some combo (option selected value) and listing on some other combobox 从某个组合(选项选定的值)中搜索并在其他组合框中列出

$("select#searchcombo").change(function(){

        $("select#listingcombo").html("<option>wait...</option>");

        var id = $("select#searchcombo option:selected").attr('value');           
     var url='index.php?option=com_example&task=methodName&format=json';
    var dat = {'id':id};
            $.ajax({ 
                type: "POST", 
                cache: false, 
                url: url, 
                 data: dat,  
                dataType: "json", 
                success: function(data) {           
            //alert(data['options']);
        $("select#listingcombo").html(data['options']);
    }, error:function(xhr, status, data) {
            //alert("Status "+status + xhr.responseText );
    }
            }); 

      }); 

Difficult to know where to start in trying to answer. 很难知道从哪里开始尝试回答。 How much of the above code is actual, and how much is for demo purposes in asking the question? 上面的代码中有多少是实际的,而在演示问题时出于演示目的有多少? I assume you wont be inserting data into the database on each page load. 我假设您不会在每次页面加载时将数据插入数据库中。 I assume you won't be hard coding your database table name with the 'jos_' prefix. 我假设您不会用'jos_'前缀对数据库表名称进行硬编码。 When doing this for real you should use '#__' without the quotes. 实际执行此操作时,应使用不带引号的'#__'。

Does a database query returning an error need to kill the script and raise a server 500 error? 返回错误的数据库查询是否需要终止脚本并引发服务器500错误? I think detecting and intercepting the error and handling gracefully would be better. 我认为检测并拦截错误并进行适当处理会更好。

After your tag you have the word date and then a - ie you close an option tag you never opened. 标签之后有单词date,然后是--即关闭从未打开过的选项标签。 I assume you intend to somehow label the select - best to do this with an actual tag rather than populating a dummy option within the select. 我假设您打算以某种方式标记选择项-最好使用实际标签来执行此操作,而不是在选择项中填充虚拟选项。

If you don't wrap your array keys in quotes you'll probably generate warnings - so do this $nt['training'] rather than $nt[training] 如果您不将数组键用引号引起来,则可能会生成警告-这样做$ nt ['training']而不是$ nt [training]

You probably need to retrieve as associative array rather than a standard ordinal array. 您可能需要检索关联数组而不是标准序数数组。

You then run a database query 'outside' of Joomla. 然后,您在Joomla的“外部”运行数据库查询。 You have retrieved the database object - you should use it rather than running mysql_query directly. 您已经检索了数据库对象-应该使用它,而不是直接运行mysql_query。

Instead of this: 代替这个:

$queryCourses="SELECT training_id,training,trainingDate FROM training"; ?>
$result = mysql_query ($queryCourses);

You probably need to do something more like this 您可能需要做更多这样的事情

// http://docs.joomla.org/How_to_use_the_database_classes_in_your_script#loadAssoc.28.29 // http://docs.joomla.org/How_to_use_the_database_classes_in_your_script#loadAssoc.28.29

$queryCourses="SELECT training_id,training,trainingDate FROM training"; ?>
$db->setQuery($queryCourses);
$db->query();

$num_rows = $db->getNumRows();
if(! $num_rows){ 
    // return or die or something - there ar no results
}
while($nt = $db->loadAssoc()){

On this line 在这条线上

echo "<option value=$nt['id']>$nt['training']</option>"; 

you should probably do this: 您可能应该这样做:

echo "<option value=\"{$nt['id']}\">{$nt['training']}</option>"; 

clearly delineating the variables with curly braces as the whole line is wrapped in quotes and remembering to put quotes around the value parameter in case you decide to add other variables into there and include spaces etc. 因为整行都用引号引起来,所以用大括号清楚地描述了变量,并记住在value参数周围加上引号,以防您决定在其中添加其他变量并包含空格等。

From your description you want to display the date to the user - you probably want to add an extra variable - maybe two within the ... part, perhaps something like: 从您的描述中,您想向用户显示日期-您可能想添加一个额外的变量-在...部分中可能是两个,也许是这样的:

echo "<option value=\"{$nt['id']}\">{$nt['training']} {$nt['trainingDate']}</option>"; 

I'm sure there are other things that I'm missing - and I've assumed your db query is broadly correct and returns results, but there should be enough pointers there to get you on the right track. 我确定还有其他事情我想念的-我已经假设您的数据库查询大致正确并且可以返回结果,但是那里应该有足够的指针来使您走上正确的轨道。

Finally - when building / populating a select list you can build data structures and get Joomla's jHTML class to do the heavy lifting for you. 最终-构建/填充选择列表时,您可以构建数据结构并获取Joomla的jHTML类来为您完成繁重的工作。 I wonder sometimes if too much abstraction creates more work than rolling your own - but hey, the option is there. 我不知道有时候,过多的抽象是否比滚动自己的工作会产生更多的工作-但是,可以选择了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM