Question

I am outputing a simple list of options from dynamic select menus using Codeigniter/MYSQL.

CONTROLLER

    $data['get_custom_fields'] = $this->db->query("
                SELECT a.custom_field_name, a.custom_field_id, 
GROUP_CONCAT('<option name=\"',c.custom_field_value_id, '\" value=\"', c.custom_field_value_id , '\">',c.custom_field_value_name , '</option>' ORDER BY c.custom_field_value_id ASC SEPARATOR ' ') as field_values
                FROM projects_custom_fields a
                JOIN projects_custom_fields_values c ON c.custom_field_id = a.custom_field_id
                GROUP BY a.custom_field_id
                ORDER BY c.custom_field_id ASC
                ");

VIEW PAGE

<?php if($get_custom_fields->result_array()) { ?>
<?php foreach($get_custom_fields->result_array() as $fRow): ?>
<tr>
    <td><label>Select <?php echo $fRow['custom_field_name']; ?></label></td>
    <td><select name="custom_field_<?php echo $fRow['custom_field_id']; ?>">
        <?php echo $fRow['field_values']; ?>
    </select>
    </td>
</tr>
<?php endforeach; ?>
<?php } ?>

This works amazingly well until I want to add the html selected attribute to certain options that are pulled from another table.

    $data['get_custom_reg'] = $this->db->query("
    SELECT custom_field_id, custom_field_value_id
    FROM projects_custom_fields_reg
    WHERE project_id = $project_id
        ");

Myself and another experienced programmer have been playing with a few ways to achieve this.

Using an array with a counter (this worked great but we couldn't increment the counter within the query) coupled with an IF statement

Our fallback option is to get rid of the single MYSQL query using GROUP_CONCAT and using multiple database calls and several PHP statements to output the code.

All help would be greatly appreciated as we have really hit a brick wall.

Thanks

Tim

Was it helpful?

Solution

Untested, try:

   SELECT a.custom_field_name, 
          a.custom_field_id, 
          GROUP_CONCAT('<option name=\"',c.custom_field_value_id, '\" value=\"', c.custom_field_value_id, CASE WHEN r.project_id IS NOT NULL THEN 'selected' ELSE '' END, '\">',c.custom_field_value_name , '</option>' ORDER BY c.custom_field_value_id ASC SEPARATOR ' ') as field_values
     FROM projects_custom_fields a
     JOIN projects_custom_fields_values c ON c.custom_field_id = a.custom_field_id
LEFT JOIN projects_custom_fields_reg r ON r.custom_field_value_id = c.custom_field_value_id
                                      AND r.custom_field_id = a.custom_field_id
                                      AND r.project_id = ?
 GROUP BY a.custom_field_id
 ORDER BY c.custom_field_id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top