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


Modify function which dynamically populates select elements to use arrays from db

我试图修改一个函数,我一直使用它来动态填充<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>

由于您只通过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属性由数组键填充,数组键将从0开始编号。这与原始的数组版本类似,但是指定另一个列名(如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');