
Originally Posted by
oceanwap
Sorry for this silly question I asked above, I found the solution immidaetly after posting this.
No worries about asking silly questions. Kudos for finding the answer, and thanks for posting it so that others might learn. However, I'm almost certain this question has been asked before on these very forums, and undoubtably been asked elsewhere.

Originally Posted by
oceanwap
Here it is:-
PHP Code:
<?php
while($row_country = mysqli_fetch_array($result_country))
{
//I get the $country_detected from IP2Country Database.
if($country_detected == $row['country_name'])
{
$select="selected=\"selected\"";
echo "<option {$select}>{$row['country_name']}</option>";
}
else
{
echo "<option>{$row['country_name']}</option>";
}
}
?>
That's almost as good as you can get it when dealing with DB query results. However, there's no need for two echo statements.
PHP Code:
while($row_country = mysqli_fetch_array($result_country))
{
//I get the $country_detected from IP2Country Database.
if($country_detected == $row['country_name']) {
$attr=' selected="selected"';
} else {
$attr = '';
}
echo "<option$attr>$row[country_name]</option>";
}

Originally Posted by
oceanwap
Actually I thought it will be similar to creating a select list for months where you want to select the current month automatically.There I used php's date() function.And a too much if else statements.But here databases made my life easy.Here is the php code I wrote for auto selecting month.
PHP Code:
<?php
date_default_timezone_set('Asia/Kolkata');
$timestamp=date(r);
$month=substr($timestamp,8,3);
if ($month==Jan) {
$select1 = 'selected="selected"';
}
...
?>
Anytime you find yourself creating numerous variable names with the same prefix, you should probably be using an array. Anytime you find yourself writing a large sequence of if statements, you should probably be using an array or a switch statement (depending in part on how similar the branches are). If the if blocks are exclusive of each other (i.e. at most one test will be true), you should make the later statements elseif statements.
PHP Code:
$months = array_combine(array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'),
array_fill(0, 12, ''));
$months[date('M')] = ' selected="selected"';
?><select><?php
foreach ($months as $mo => $attr) {
echo "<option$attr>$mo</option>";
}
?></select><?php
Also, strings should always be quoted; you never know what constants may be defined later on or keywords added to the language. You quoted neither the date format string nor the short month names.