Insert a data from a Combobox (PHP) into the Database

Asked

Viewed 985 times

0

Hello, I’m putting together a system for the college project. I have a relationship between City-State. Well, the state CRUD is already working and storing in the Database, when I will register a city, this city needs a registered state, so the fields to register the city.

"City name"(input type text) and UF(Combobox already populated through a select) When I try to store in the bank the name of the city and the state coming from a combobox does not appear anything in the bank, even pointing no error. How I perform the db Insert using a state in the combobox

<?php
include 'inc/funcoes.php';
$banco = abrirBanco();
?>
<html>
    <head>
        <title>Cadastro de Cidade</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <form name="Cidade" action="inc/funcoes.php" method="POST">
            Nome da Cidade:
            <input type="text" name="cidade" size="30" />
            UF:
            <select name="estados">
                <option value="">Selecione</option>
                <?php
                $sql = "SELECT * FROM estado";
                $resultado = $banco->query($sql);
                while($row_estados = $resultado->fetch_array()){ 
                ?>
                <option value="<?=$row_estados['idestado']?>"><?=$row_estados['nomeestado']?></option>
                <?php
                }
                ?>
            </select><br><br>
            <input type="hidden" name="acao" value="inserirCidade"/>
            <input type="submit" value="Cadastrar Cidade">
            <input type="reset" value="Limpar Dados">
        </form>
    </body>
</html>

Function of stand of combobox Line:17 - 26

  • In this code you showed, you’re not entering anything into the database.

  • The table cidade has the column for the foreign key estado?

  • was recording with the wrong name in the table, but to simplify I decided to do as the friend below said, using a function in javascript to fetch the combobox data

2 answers

0


If I understood your question well after popular the Combobox (CB), my suggestion would be through Javascript (or jQuery), fetch the value that is in the CB and send to a PHP where will do the query SQL to add this value to your Database.

Jquery(JS):

$(input[type='submit']).on("click", function(){
       var campoCB = $(select[name='estados']).val();
    $.ajax({
        url: 'script.php',
        type: 'POST' //ou GET
        data: {campo: campoCB},
        dataType: 'json' //por exemplo, pode ser, csv, text, etc...
        success: function(data){
            //código a executar depois de enviar o parametro para o servidor
        }
    })
}

in PHP receives the field and writes the SQL query here with the parameter that passed JS

PHP:

$campo = $_POST['campo'];

====EDITION====

If you don’t need an asynchronous call (AJAX), you can send the argument for example, by POST/GET through the form, when you commit. Send and receive the argument in PHP as shown above.

  • Why submit an asynchronous request and not just the normal submission of the form in a synchronous request?

  • You’re right, it’s true. It’s not necessary. I got carried away by a job I’m doing now, so I used ajax. I’ve already edited the answer. Thank you!

  • Thanks, it worked, I was able to record in the bank, another small doubt... I have the registration of person who depends on this city and state, have how I select the State, and then, just return to me, the cities that are linked with the id of this state, I tried using the google jsapi script. but it does not return any city, I will post the codes

  • Function using Google JSAPI: https://pastebin.com/w24f9dBA Select city inc/subcategory city.php: https://pastebin.com/tHfeKSFN

  • You can make this association through SQL using a JOIN, if in the person table you have reference to the foreign key of the city and state table. If you haven’t noticed, you can post the relational schema of the tables, pf?

  • posted a photo with the relational model

  • From what I understand, what you want is an SQL query that returns the cities belonging to a state, right? If I understand correctly, the query is as follows: SELECT nomecidade FROM cidade c JOIN estado e ON c.estado_idestado = e.idestado

  • It worked until a certain point fraza0, in fact, it is searching all the cities, what I need is: first I select the state in a combobox, and soon after that in another combobox returns me only cities that have the foreign key of that state.

Show 3 more comments

0

Here is the part of the relations between State-City-Address-Person.

Browser other questions tagged

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