修改函数,动态填充select元素以使用db中的数组

时间:2013-03-27 01:25:17

标签: php arrays html-select populate

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

修改后的函数会创建元素,但它只会添加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>

原始功能&amp;填充元素的代码

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>

1 个答案:

答案 0 :(得分:1)

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

// 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');