retrieve data in a list for editing

0

In an edit page of the registration data, how to fill a selection with the information originally saved.

Ex. In the registration form, a city was selected in a select. After saving, you have the option to edit the data, but I am not able to display in the select the original city, and list the others, for change option.

I'm trying to php this operation, but I'm not getting it. How can I be doing?

    
asked by anonymous 07.04.2016 / 21:07

1 answer

1

I think the easiest way is this:

Save all cities / states in a separate table in the database. Let's suppose that this table is formed by the columns:

id | City | UF

Then I would do the following:

<?php
$query = mysql_query("SELECT * FROM cidades ORDER BY cidade ASC");

echo '<select name="cidade">';
while($exe = mysql_fetch_array($query)){

$selected = ($exe['id'] == $id_salva_da_cidade_na_outra_tabela) ? 'selected' : '';

echo '<option value="'.$exe['id'].'" '.$selected.'>'.$exe['cidade'].' - '.$exe['uf'].'</option>';
}
echo '</select>';
?>

If you have cities saved in array and not in database:

<?php
$array = array('sp'=>'São Paulo', 'sp'=>'Osasco', 'rj'=>'Rio de Janeiro');

echo '<select name="cidade">';
foreach($array as $uf=>$cidade){

$selected = ($uf == $uf_salva_no_banco_de_dados) ? 'selected' : '';

echo '<option value="'.$uf.'" '.$selected.'>'.$cidade.' - '.$uf.'</option>';
}
echo '</select>';
?>

I use these outputs when I have to auto-fill a select to edit data.

    
07.04.2016 / 21:18