1

我正在尝试修改我一直用来动态填充<select>元素以使用数据库中的数组的函数。原始函数使用硬编码数组来填充元素,并预先选择与 db 值匹配的选项。

修改后的函数创建了元素,但它只添加了数据库中的第一个值。我怎样才能修改它,以便它循环遍历所有应该添加到<select>元素的值?

PHP 函数和查询

<?php
function printSelectOptions($dataArray, $currentSelection) {
    foreach ($dataArray as $key => $value) {
        echo '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . $value . '</option>';
    }
}
try {  
    $stmt = $conn->prepare("SELECT * FROM student");  
    $stmt->execute();
    }catch(PDOException $e) {
    echo $e->getMessage();
} 
$row = $stmt->fetch();
?>

填充选择元素

<select name="fname">
    <?php
        echo printSelectOptions(array($row['fname'])); 
    ?>
</select>

填充元素的原始函数和代码

function printSelectOptions($dataArray, $currentSelection) {
    foreach ($dataArray as $key => $value) {
        echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
    }
}

<select name="fname">
    <?php
        $options = array("John"=>"John", "Mary"=>"Mary", "Elizabeth"=>"Elizabeth");
        $selected = $row['fname'];
        echo printSelectOptions($options, $selected); 
    ?>
</select>
4

1 回答 1

1

由于您只通过 获取了一行fetch(),因此只有一个值被传递到您的函数printSelectOptions()中。相反,通过获取所有行fetchAll() 并修改您的函数以接收完整数组,以及一个字符串,该字符串是您要从中打印的列名(数组键)。

// All rows into $rows...
$rows = $stmt->fetchAll();

// Make the function accept the full 2D array, and 
// a string key which is the field name to list out:
function printSelectOptions($dataArray, $currentSelection, $fieldname) {
    // String to hold output
    $output = '';
    foreach ($dataArray as $key => $value) {
        // Rather than echo here, accumulate each option into the $output string
        // Use the $fieldname as a key to $value which is now an array...
        $output .= '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . htmlspecialchars($value[$fieldname], ENT_QUOTES) . '</option>';
    }
    return $output;
}

然后调用函数为:

echo printSelectOptions($rows, $currentSelection, 'fname');

现在的方式是,选项的 value 属性由数组键填充,该键将从零开始编号。id这类似于您的原始数组版本,但指定另一个列名(如键列) 可能更有用。

// This one also takes a $valuename to use in place of $key...
function printSelectOptions($dataArray, $currentSelection, $valuename, $fieldname) {
    // String to hold output
    $output = '';
    foreach ($dataArray as $key => $value) {
        // Rather than echo here, accumulate each option into the $output string
        // Use the $fieldname as a key to $value which is now an array...
        $output .= '<option ' . (($value[$valuename] == $currentSelection)) . ' value="' . $value[$valuename] . '">' . htmlspecialchars($value[$fieldname], ENT_QUOTES) . '</option>';
    }
    return $output;
}

并将被称为:

    echo printSelectOptions($rows, $currentSelection, 'id', 'fname');
于 2013-03-27T01:36:39.787 回答