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
https://forums.phpfreaks.com/topic/288521-load-correct-cell-on-edit/
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";

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.

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";

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.