Reputation: 784
I have state table having state_id and state_name. I am displaying it directly in template file like below..
<select name="state" id="state" class="select-submit2">
<option value="">Select state</option>
<?php
$result=$wpdb->get_results("select * from states");
foreach($result as $row) {
$state_id=$row->state_id;
$state_name=$row->state_name;
echo '<option value='.$state_id.'>'.$state_name.'</option>';
}
?>
</select>
But when I want to edit that how do I show first selected state name.????
Edit page url... whitecode.in/demo/plotsup_plot/new-property/?listing_edit=6795
This is my function code in function.php file
function getcity(){
global $wpdb;
if($_POST['state'])
{
$id=$_POST['state'];
$property_id = $_GET['listing_edit'];
$district = get_post_meta($property_id, district, true);
$result=$wpdb->get_results("SELECT * FROM districts WHERE state_id='$id'");
//$wpdb->get_results($query);
foreach($result as $row) {
$city_name = $row->district_name;
$city_id = $row->district_id;
?>
<option value="<?php echo $city_id; ?>" <?php if($district == $city_id){ echo
'selected="selected"';} ?>><?php echo $city_name; ?></option>
<?php
//echo '<option value="'.$city_id.'">'.$city_name.'</option>';
}
}
}
Upvotes: 0
Views: 11014
Reputation: 198
As per as discussed in the previous comments, I guess that property is a custom post type in your site. So if that is the scenario then this should be the solution.
<select name="state" id="state" class="select-submit2">
<option value="">Select state</option>
<?php
$property_id = $_GET['listing_edit']; //the PROPERTY_ID should be replaced with the original id might be ina get variable or any process by which you are using for the edit page.
$property_state = get_post_meta($property_id, META_KEY_STATE, true); //META_KEY_STATE is the meta_key name you use to store the value of the state in the postmeta table
$result=$wpdb->get_results("select * from states");
foreach($result as $row) {
$state_id=$row->state_id;
$state_name=$row->state_name;
?>
<option value="<?php echo $state_id; ?>" <?php if($property_state == $state_id){ echo 'selected="selected"';} ?>><?php echo $state_name; ?></option>
<?php
}
?>
</select>
Try this and let me know if you face any issues.
Upvotes: 3
Reputation: 593
If this is what you are looking for?
<select name="state" id="state" class="select-submit2">
<option value="">Select state</option>
<?php
$result=$wpdb->get_results("select * from states");
foreach($result as $row) {
$state_id=$row->state_id;
$state_name=$row->state_name;
if($state_id == SELECTED_STATE_ID)
echo '<option value='.$state_id.' selected>'.$state_name.'</option>';
else
echo '<option value='.$state_id.'>'.$state_name.'</option>';
}
?>
</select>
just replace SELECTED_STATE_ID with variable which contains which state is selected
Upvotes: 0