在select选项中显示一些值,在DB中插入值不同

时间:2014-04-29 23:24:30

标签: php html joomla html-select

我有一个包含这样的值的表:

table CECO
CECO_cod     CECO_name
109003       APRENDIZ SENA

然后我尝试在HTML中显示这样的信息选择这样,它工作正常,因为它只显示 CECO_name:

$db        = &JFactory::getDBO();
$query     = "SELECT CECO_name FROM CECO";
$db->setQuery($query);
$result    = $db->loadObjectList();
$CECO_name  = $result[0]; 

echo " <select id='CECO' name='CECO' >";
foreach($result as $CECO_name)
{
 echo "<option >".$CECO_name->CECO_name."</option>";
}
echo "</select>"

但我真正想要的是显示CECO_name,值将是CECO_cod,如下所示:

echo "<option value=".$CECO_cod->CECO_cod." >".$CECO_name->CECO_name."</option>";

解决方案:

$db =& JFactory::getDBO();
$query = "SELECT CECO_cod as value,CECO_name as text  FROM CECO";
$db->setQuery($query);
$result = $db->loadObjectList();

$options = array();
$options[] = JHTML::_('select.option', '0', 'Select');
foreach($result as $row)
{
$options[] = JHTML::_('select.option', $row->value, $row->value." - ".$row->text);
}
$dropdown = JHTML::_('select.genericlist', $options, 'CECO_1"_"', '="_"', 'value', 'text');
echo $dropdown; 

2 个答案:

答案 0 :(得分:2)

由于您使用的是Joomla,因此API中已经存在一些有用的东西。

$db = JFactory::getDbo(); //
$query = $db->getQuery(true); // the true param clears the query and gets a new object

$query->select('CECO_cod', 'CECO_name');
$query->from('#__CECO'); // this is assuming your table has a prefix.

$db->setQuery($query); // set the query object to the DB object

$list = $db->loadObjectList(); // this gives you an array of objects

现在你有一个对象数组,你可以实际使用JHTML来呈现HTML列表。 https://github.com/joomla/joomla-cms/blob/staging/libraries/cms/html/select.php#L81

所以你会这样做:

echo JHtmlSelect::genericlist($list, 'my list', 'CECO_cod', 'CECO_name');
/* note the parameters at the end denote the 'value' 
*  and 'text' part of the select list. 
*  You might need to play with this a bit.
*/

这应该为你生成选择列表,并且比循环并构建自己的选择列表更清晰。

您也可以考虑使用JForm来构建选择列表。不知道你在做什么,但我建议你尽可能简化生活。

答案 1 :(得分:0)

您需要选择这两个字段才能访问返回对象中的数据。

$query     = "SELECT CECO_cod, CECO_name FROM CECO";

然后您可以在选择框中找到所需的信息:

<?php
/* create new database object */
$mysqli = new mysqli("localhost", "user", "password", "so");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* query for all of the needed data */
$query = "SELECT CECO_cod,CECO_name FROM CECO";

/* begin select */
echo "<select id=\"CECO\" name=\"CECO\" >";

/* check to make sure we have a result from the query */
if($result = $mysqli->query($query)) {
    /* if we have a result we can populate the select data */
    while ($obj = $result->fetch_object()) {
        echo "<option value=".$obj->CECO_cod." >".$obj->CECO_name."</option>";
    }
    /* if we failed for some reason, most likely the query was to blame */
} else {
    echo "error, query was not successful.<br>";
    }

    echo "</select>";

/* close connection */
$mysqli->close();

?>

我在本地测试了这段代码的正确性,请注意它是如何评论的,无论你的写作代码有多短或多长,我都鼓励你这样做。