php - How to set default value of a select dynamically from database using smarty? -
i have select
this:
<select class="fruitsselect" name="fruits"> <option value="apples">apples</option> <option value="bananas">bananas</option> <option value="oranges">oranges</option> </select>
and know can set default value if use selected
attribute.
<select class="fruitsselect" name="fruits"> <option value="apples">apples</option> <option value="bananas" selected>bananas</option> <option value="oranges">oranges</option> </select>
but trying that, value retrieve database (i send html
via php
) option retrieve database selected
option (the default option).
i have value on html not know how make selected option because can change. using smarty
, trying make ifs statements cannot out.
how can compare value retrieve database value of select
, make selected option?
thanks in advance!
since asked smarty templating, pretty easy. use html_options
template their example file , pass identifier selected attribute.
contents of index.tpl
:
{html_options name=fruits options=$myoptions selected=$myselect}
the real messy part getting array populated database. since didn't specify platform, used mysql.
first set simple database table model example boolean column selected state. can constrained or set like, note example if multiple set true, use last 1 selected. , used id's bonus because more useful non-trivial scenario. if still want use same value option text, find , replace $row['id']
$row['fruit']
drop table if exists fruits; create table fruits ( id int primary key auto_increment, fruit varchar(30), selected boolean ); insert fruits (fruit,selected) values ('apples',false), ('bananas',true), ('oranges',false);
now use php retrieve data, create smarty object, set values, , display.
<?php require_once(__dir__.'/vendor/smarty/smarty/libs/smarty.class.php'); $database_server = "localhost"; $database_username = "username"; $database_password = "p@55w0rd"; $database_name = "example_database"; // connect database $mysqli = new mysqli($database_server, $database_username, $database_password, $database_name); if ($mysqli->connect_error) trigger_error('connect error: '.$mysqli->connect_error, e_user_error); // records $sql = "select id, fruit, selected fruits"; $result = $mysqli->query($sql); while ($row = $result->fetch_array(mysqli_assoc)){ // set array index of fruit id $fruits[$row['id']] = $row['fruit']; // id of selected fruit if ($row['selected'] == true) $selected = $row['id']; } // create object $smarty = new smarty; $smarty->assign('myoptions', $fruits); $smarty->assign('myselect', $selected); // display $smarty->display('index.tpl');
and results in following output:
<select name="fruits"> <option value="1">apples</option> <option value="2" selected="selected">bananas</option> <option value="3">oranges</option> </select>