Combine function that populates `select` elements with function that pre-selects options matching db values

I want to modify function checkSelectedOption so that I don't have to hardcode the array every time it's called.

The 1rst function pre-selects the option matching the information in the db, but it uses hardcoded arrays to populate select elements. The 2nd function creates arrays from db values and dynamically populates select elements. How can I combine these two functions so that I can populate select elements dynamically, and then pre-select the option matching the information in the db?

Function checkSelectedOption populates the element with the values specified in array "$options", and then pre-selects the option matching the information in the "customer_info" table of the db. This function currently requires that the arrays be hardcoded, and I want to replace this part of the function with the method from function printSelectOptions which uses arrays created from db values.

Function printSelectOptions populates select elements from values fetched from the db. It does this by creating an array with the values in the column fetched from the "form_fields" table.

Function checkSelectedOption

function checkSelectedOption($dataArray, $currentSelection) {
    foreach ($dataArray as $key => $value) {
        echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
    }
}
try {  
$stmt = $conn->prepare("SELECT * FROM customer_info WHERE user_id = :user_id");  
$stmt->bindValue(':user_id', $user_id); 
$stmt->execute();
} catch(PDOException $e) {
    echo $e->getMessage();
} 
$row = $stmt->fetch();

To call function

<select name="first_name">
    <?php
    // Populates the element with values from array $options         
    $options = array("John"=>"John", "Robert"=>"Robert");
    $selected = $row['first_name'];
    echo checkSelectedOption($options, $selected);
    ?>
</select>            

Function printSelectOptions

function printSelectOptions($dataArray, $currentSelection, $fieldname) {
    $output = '';
    foreach ($dataArray as $key => $value) {
    // Only add to array if row has value
    if ($value[$fieldname] !="" && $value[$fieldname] !="Null") {
            $output .= '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . str_replace('_', ' ', $value[$fieldname]) . '</option>';
        }
    }
    return $output;
}
try {  
    $stmt = $conn->prepare("SELECT * FROM form_fields");  
    $stmt->execute();
} catch(PDOException $e) {
    echo $e->getMessage();
} 
$rows = $stmt->fetchAll();

To call function

<select name="first_name">
    <?php 
    // Dynamically populates element with array created from column first_name
    echo printSelectOptions($rows, $currentSelection, 'first_name');
    ?>
</select>  

Answers


@metal_fan, I'm not sure what you're referring to, can you elaborate a bit?

600 chars won't be enough, I guess.

How can I combine these two functions so that I can populate select elements dynamically and then pre-select the option matching the information in the db?

You have to fetch the data you need then compare it against a value "inside" selectbox inside a loop (or it would be a hell).

PHP itself is meant to be used as a template engine. That means, people should use it as a template engine - Don't print/echo html tags, inject php "things" instead.

All what you're doing now doesn't make sense at all. The common solution is to create a helper function that does calculation.

Remember, one function should only do single task. If you have several ones, create a function for each one.

UPDATE Well, I'm kinda confused even more now, after your edit.

// Assume that array we got from the table looks like:
$array = array('John' => 'John', 'Dave' => 'Dave', 'Jason' => 'Jason');

$__AGAINST__ = 'Jason'; // <-- VERY IMPORTANT

function is_selected($expected, $actual){

    if ( $expected === $actual ){

        print 'selected="selected"';
    }
}

?>

<select>

    <?php foreach($array as $key => $val):?>

    <option value="<?php echo $key; ?>" <?php is_selected($key, $__AGAINST__); ?>><?php echo $val; ?></option>

    <?php endforeach; ?>

</select>

$__AGAINST__ you would take from configuration or something like that. This is what you're comparing against.

Now replace $__AGAINST__ = 'Jason'; with $__AGAINST__ = 'Dave'; You see how it works? The core idea is to iterate over $array and compare $key against something. Nothing more.

UPDATE 2

I guess you got an idea how "select against" works. But you didn't understand what I've told you at all :( Look at this:

$output .= '<option ' . is_selected($key, $__AGAINST__) . ' value="' . $key . '">' . str_replace('_', ' ', $value[$fieldname]) . '</option>';

You're keep making the same mistake again and again. PHP itself is meant to be used as a template engine. You should avoid printing/echoing HTML tags. Why? What if you decide to replace that select with another element (say Jquery ComboBox plugin). What happens then? You would have to re-factor the "generation" logic itself as well as a presentation. Sounds so bad. Why sounds bad? This is because presentation should be totally decoupled from application/generation logic. Why should be decoupled? Flexibility, Maintainability would answer this question, I guess.

Keep your templates as dumb as possible They should NEVER do any calculations directly. If you want to calculate something within a HTML template, then define a function somewhere in bootstrap.php (or the like), but not inside a markup itself.

PHP is meant to be used as a template engine. But what does it really mean?

This means (we are not in Perl/Python), you should ALWAYS avoid code like this one:

$ouptut = '<option>' . $foo . '</option>';
echo '<table>';
echo '<tr>';
echo '<td>' . $bad . '</td>';
echo '</tr>';

But write something like this instead:

<select>
  <option><?php echo $foo; ?></option>
</select>

Keeping this thing in mind, you would keep your HTML things totally decouple from PHP parser. Which is great for future maintains.


Need Your Help

Why are the Scala libraries implemented with mutable state?

scala immutability

Why are some methods in Scala's standard libraries implemented with mutable state?

Yii Bootstrap TbGridView

twitter-bootstrap yii frameworks yii-extensions yii-widgets

For some reason my filtering isn't working correctly inconjunction with the pager on my Yii site, I have the following view which uses the Yii Bootstrap TbGridView widget to display some tabular da...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.