how to use php condition in html option tag

Ehsan Jafari

i have this function and i want use "selected" attribute in "option" tag when $selected is equal to $row['id']. please pay attention it's not an usual html tag between php codes, pay attention html option tag add to $output variable every time in while loop.

public function getCategoriesList(&$output = '',
                                      $parent = 0, $seprator = '', $selected=1)
    {
        $sql = "SELECT * FROM categories WHERE `parent_id` = $parent ";
        $stmt = $this->pdoConnection->prepare($sql);
        $stmt->execute();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            $output .= "<option value=".$row['id']." ($row[id]==$selected)? selected :''>
                            ".$seprator.$row['title']."
                        </option>";


          $this->getCategoriesList($output, $row['id'],
                    $seprator . ' - ');

        }

        return $output;

    }
MH2K9

You can make a separate condition for selected attribute. Example:

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $selected = $row['id'] == $selected ? "selected='selected'" : '';
    $output .= "<option value='{$row['id']}' {$selected}>{$seprator}{$row['title']}</option>";

    $this->getCategoriesList($output, $row['id'], $seprator . ' - ');
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive