Jump to content

Load correct cell on edit


jpopuk

Recommended Posts

Hi, I have setup a little post function where you can edit it. When the data has been submitted it sends all data to a database.

 

When I go to edit a post this is how I have each dropdown to load the correct option:

<select name="ad_type">
	<option selected="selected"><?php echo $post['ad_type']; ?></option>
	<option>-- Please Select --</option>
	<option value="For Adoption">For Adoption</option>
	<option value="For Sale">For Sale</option>
</select>

How would I do it so it would automatically select the correct option rather than having it add another option at the top?

 

Thanks

Link to comment
Share on other sites

Check which option matched the current value and mark it as selected

$opts = array('To let', 'For adoption', 'For sale');

echo "<select name='ad_type>\n<option value = ''>--Please select--</option>\n";
foreach ($opts as $opt) {
    $sel = $opt == $_POST['ad_type'] ? 'selected="selected"' : '';
    echo "<option value='$opt' $sel> $opt</option>\n";
}
echo "</select>\n";
Link to comment
Share on other sites

The options are pulled in from a database so the array part would not be the way to go for me.

 

I have tried this:

<option value="<?php echo $post['ad_type']; ?>"<?php echo $post['ad_type'] == $post['ad_type'] ? ' selected="selected"' : ''; ?>><?php echo $post['ad_type']; ?></option>

But this did not work.

Link to comment
Share on other sites

Just the same except you loop through returned rows from the query instead of the array elements

$sql = "SELECT ad_type FROM mytable";
$res = $db->query($sql);

echo "<select name='ad_type>\n<option value = ''>--Please select--</option>\n";
while ($row = $res->fetch_assoc()) {
    $sel = $row['ad_type'] == $_POST['ad_type'] ? 'selected="selected"' : '';
    echo "<option value='{$row['ad_type']}' $sel> {$row['ad_type']}</option>\n";
}
echo "</select>\n";
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.