List states, cities and neighborhoods on registration form

Asked

Viewed 8,949 times

12

I have a table called "ad", where I need to register the information coming from other 03 tables, are they:

Tables of States, Cities and Neighborhoods.

The objective is that the user himself makes the registration of the properties via form, acquiring the information about the property, thus assembling his advertisement.

I have tried to bring the information via Select from each table, but I have not succeeded, and I have no idea how to do this.

I thought about using Combobox but I couldn’t either.

I am attaching the images of the tables for friends to analyze, and who knows how to get me to record the information in the table advertising, via php and Sql form.

The information included in the "advertisement" table was inserted directly in the BD.

I also attach the address to be analyzed, because the search system with the combobox is working by registering directly in the Database.

Access address for testing: http://www.buziosnegocios.com.br/

Tabela Anuncio:inserir a descrição da imagem aqui

Table States:

inserir a descrição da imagem aqui

Table Cities:

inserir a descrição da imagem aqui

Table Neighborhoods:

inserir a descrição da imagem aqui

If friends can give me this help and show me how to register in a way that looks like this in the table "advertisement", ie the information cross to succeed in the search.

Big hug to all, and my thanks for the attention.

  • Can’t you build php code or queries? In my view select and combo box are the same thing.

  • You don’t know how to assemble the page, you don’t know how to link the data, how to get the data from the page or you don’t know anything? Your question was extremely vague about what you want.

1 answer

9

Normalization

First I recommend normalizing your ad table, if you already have tables to store states, cities and neighborhoods, you only need to have the neighborhood code in the ads table, because with this code you will be able to recover the other information. Would look like this:

Table Ads

id               int(11)     unsigned     not null     auto increment
cod_bairro       int(11)     unsigned     not null
foto             varchar(250)

Note that now your table only has the neighborhood code that is mandatory, however recovering the neighborhood record, It is possible to recover the city, and then can recover the state.

In some cases it is interesting to do as you did, but it is preferable to use a layer of denormalized cache, but that is another matter.

Bairro Table

id               int(11)     unsigned     not null     auto increment
cod_cidade       int(11)     unsigned     not null
nome             varchar(250)

Table City

id               int(11)     unsigned     not null     auto increment
cod_estado       int(11)     unsigned     not null
nome             varchar(250)

Table State

id               int(11)     unsigned     not null     auto increment
nome             varchar(250)
uf               char(2)

Putting together the form

Your form must have 3 fields select and one for the photo attachment. To mount you will need to search in your database only the list of states, however you will have to create two other functions or files to list cities and neighborhoods according to what the user select.

For example, the user when filling the form selects a state, then an Ajax call is made to get the cities by passing the code of the selected state. And the same happens when selecting the city and getting the list of neighborhoods.

In the code below was used PDO for queries in the database and jQuery for Javascript.

Seeking state

$sqlEstado = 'SELECT * FROM estado ORDER BY nome ASC';
$resEstado = $conexao->prepare($sqlEstado);
$resEstado->execute();
$estados = $resEstado->fetchAll();

Form

<form action="salvar_anuncio.php" method="post" enctype="multipart/form-data">

    <label for="estado">Estado:</label>
    <select name="estado" id="estado" required>
        <option value="">Selecione</option>
        <?php foreach ($estados as $estado) { ?>
            <option value="<?php echo $estado['id'] ?>"><?php echo $estado['nome'] ?></option>
        <?php } ?>
    </select>

    <label for="cidade">Cidade:</label>
    <select name="cidade" id="cidade" disabled required>
        <option value="">Selecione um estado</option>
    </select>

    <label for="bairro">Bairro:</label>
    <select name="bairro" id="bairro" disabled required>
        <option value="">Selecione uma cidade</option>
    </select>

    <label for="foto">Foto:</label>
    <input type="file" name="foto" id="foto">

    <button type="submit">Salvar</button>
</form>

Javascript for the form

$(document).ready(function() {
    $('#estado').on('change', function() {
        $.ajax({
            type: 'POST',
            url: 'lista_cidades.php',
            dataType: 'html',
            data: {'estado': $('#estado').val()},
            // Antes de carregar os registros, mostra para o usuário que está
            // sendo carregado.
            beforeSend: function(xhr) {
                $('#cidade').attr('disabled', 'disabled');
                $('#cidade').html('<option value="">Carregando...</option>');

                $('#bairro').html('<option value="">Selecione uma cidade</option>');
                $('#bairro').attr('disabled', 'disabled');
            },
            // Após carregar, coloca a lista dentro do select de cidades.
            success: function(data) {
                if ($('#estado').val() !== '') {
                    // Adiciona o retorno no campo, habilita e da foco
                    $('#cidade').html('<option value="">Selecione</option>');
                    $('#cidade').append(data);
                    $('#cidade').removeAttr('disabled').focus();
                } else {
                    $('#cidade').html('<option value="">Selecione um estado</option>');
                    $('#cidade').attr('disabled', 'disabled');

                    $('#bairro').html('<option value="">Selecione uma cidade</option>');
                    $('#bairro').attr('disabled', 'disabled');
                }
            }
        });
    });

    $('#cidade').on('change', function() {
        $.ajax({
            type: 'POST',
            url: 'lista_bairros.php',
            dataType: 'html',
            data: {'cidade': $('#cidade').val()},
            // Antes de carregar os registros, mostra para o usuário que está
            // sendo carregado.
            beforeSend: function(xhr) {
                $('#bairro').attr('disabled', 'disabled');
                $('#bairro').html('<option value="">Carregando...</option>');
            },
            // Após carregar, coloca a lista dentro do select de bairros.
            success: function(data) {
                if ($('#cidade').val() !== '') {
                    // Adiciona o retorno no campo, habilita e da foco
                    $('#bairro').html('<option value="">Selecione</option>');
                    $('#bairro').append(data);
                    $('#bairro').removeAttr('disabled').focus();
                } else {
                    $('#bairro').html('<option value="">Selecione uma cidade</option>');
                    $('#bairro').attr('disabled', 'disabled');
                }
            }
        });
    });
});

File list_cities.php

<?php
// Uma forma de obter $_POST['estado'] mais segura
$codEstado = filter_input(INPUT_POST, 'estado', FILTER_VALIDATE_INT);

$sqlCidade = 'SELECT * FROM cidade WHERE cod_estado = :codestado ORDER BY nome ASC';
$resCidade = $conexao->prepare($sqlCidade);
$resCidade->execute(array(
    ':codestado' => $codEstado
));
$cidades = $resCidade->fetchAll();
?>

<?php foreach ($cidades as $cidade) { ?>
    <option value="<?php echo $cidade['id'] ?>"><?php echo $cidade['nome'] ?></option>
<?php } ?>

File list_neighborhoods.php

<?php
// Uma forma de obter $_POST['cidade'] mais segura
$codCidade = filter_input(INPUT_POST, 'cidade', FILTER_VALIDATE_INT);

$sqlBairro = 'SELECT * FROM bairro WHERE cod_cidade = :codcidade ORDER BY nome ASC';
$resBairro = $conexao->prepare($sqlBairro);
$resBairro->execute(array(
    ':codcidade' => $codCidade
));
$bairros = $resBairro->fetchAll();
?>

<?php foreach ($bairros as $bairro) { ?>
    <option value="<?php echo $bairro['id'] ?>"><?php echo $bairro['nome'] ?></option>
<?php } ?>

SQL to search Ads\

SELECT
    a.`id`,
    a.`foto`,
    e.`nome`,
    e.`uf`,
    c.`nome`,
    b.`nome`
FROM `anuncio` AS a
INNER JOIN `bairro` AS b
ON a.`cod_bairro` = b.`id`
INNER JOIN `cidade` AS c
ON b.`cod_cidade` = c.`id`
INNER JOIN `estado` AS e
ON c.`cod_estado` = e.`id`
WHERE
    -- Condicoes
  • 1

    Hello marcusagm, I would like to thank your tip, because with it opened my mind and I managed to do what I wanted. Because your tip to register only the codes of the state, cities and neighborhoods solved my problem. Once finished and confirm the functionality I will post as was the code along with the form, thanks? Again thank you for your help,

  • Good afternoon marcusagm, I am testing your code, but in the form I select any state and do nothing, can give me an idea?

  • Good can be several things, added jquery? Is the id referenced in Javascript with the same name? Ex input id="estado and $('#estafo') if that’s not so, open Firebug and see if on console you’re not accusing anyone of error

  • I took the code exactly as it is here, made a connection include in all files, added the jquery just below the </head>.... I am reviewing everything but I can’t find the reason for the problem. In the Chrome console I couldn’t find anything, I will try firebug

  • You can change from $('estado').on('change', ... to of $('estado').change(function () {...

  • If so is jquery version the problem

  • I put jquery 1.8.2 and it worked, it enables the city but you don’t find any city, it’s circled in red. What does that mean? Thanks for the tips.

  • Do you have a city registered to the selected state? If the border has turned red it can be pq the case of the focusing field is set with red border or pq has required field formatting when submitting the form. For some reason had an attempt to send

  • Ah, one more detail I forgot, if for example I go to the neighborhood and start the state again, the neighborhood gets the old selections. You can block/change that?

  • have yes I will update the reply and send you in chat

  • Dude, if I had to move the "state" field back to the last combo, how would I do it? I tried to insert date: {'state': $('#state'). val()}, under the date: {'city': $('#city'). val()}, but did not. Thank you!

  • data: {'cidade': $('#cidade').val(), 'estado': $('estado').val()}

  • Thanks buddy! It worked, I had to deal with $resBairro->execute(array( ':codcidade' => $codCidade ); and then it worked.

  • What if I wanted to set the return on an input, not on a combo? the list_city returns value, but I can’t set it. Got an idea? I did it this way: <?php foreach ($returns as $return) { ? > <input type "text" value="<? php echo $return['user'] ? >"><? php echo $return['user'] ? > <? php }

  • There is no point to this. Input text allows you to just type any text and not select an option. If you want the person to type and appear the options below use some autocomplete plugin.

  • Actually I select a value and the return would be placed on that input. It’s like a change form you know? If I put a combo the value appears, but if I switch to an input field the value does not appear...

  • If you want to display all text fields you will have to replace select to a div

Show 13 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.