How do I dynamically return data from Mysql columns in each update form input?

Asked

Viewed 180 times

0

Description

First, the field Seleciona jogo returns all registered games (This field works as the selection of the game ID to update given game) and what I would like to know is how do so that the other fields below the Seleciona jogo the values in the database columns are dynamically filled in to facilitate the update process.

Advantages of this:

  • Saves time as the user chooses the field he wants to update without having to fill in change the other fields.

Example:

  • Selects game: Watch Dogs 2 (ID).
  • Name: Watch Dogs 2 (value that is in the column game table nome).
  • Price: 23,99 (value that is in the column game table preco is automatically shown in the field Preço).
  • Platform: PC (value that is in the column game table plataforma is automatically shown in the field Plataforma).
  • Developer: Ubisoft (value that is in the column game table desenvolvedora is automatically shown in the field Desenvolvedora).
  • The only field I will update is the preco, of 23,99 for 19,99. After that I press the button Atualizar jogo I didn’t even have to fill in the other fields I didn’t want to update (because if I leave the blank fields the columns are empty in the database, except for the column preco).

The image of the form

A imagem

PHP code

<?php
        require_once 'conexao.php'; 
        if(isset($_POST['Atualizar'])){  
            $cd_jogo = $_POST['cd_jogo'];
            $nome = $_POST['nome'];
            $preco = $_POST['preco'];
            $plataforma = $_POST['plataforma'];
            $desenvolvedora = $_POST['desenvolvedora'];
            try {
                $update = "UPDATE jogo SET nome = :nome, cpf = :cpf, preco = :preco, 
                plataforma = :plataforma, desenvolvedora = :desenvolvedora WHERE cd_jogo = :cd_jogo";
                $atualiza = $conexao->prepare($update);
                $atualiza->bindValue(':cd_jogo',$cd_jogo);
                $atualiza->bindValue(':nome',$nome);
                $atualiza->bindValue(':preco',$preco);
                $atualiza->bindValue(':plataforma',$plataforma);
                $atualiza->bindValue(':desenvolvedora',$desenvolvedora);
                $atualiza->execute();   
            } catch (PDOException $falha) {
                echo "A atualização não foi feita".$falha->getMessage();
            }
        }
        $seleciona = $conexao->query("SELECT cd_jogo, nome FROM jogo");
        $resultado = $seleciona->fetchAll();
    ?>

Form

<form method="POST">
        <p> Seleciona jogo:
        <select name="cd_jogo" required="">
            <option value=""> </option>
            <?php
                foreach ($resultado as $v) {
                    echo "<option value='{$v['cd_jogo']}'>{$v['nome']}</option>";
                }
            ?>
        </select>
        </p>
        <p> Nome: <input type="text" name="nome" size=30 maxlength="30" required=""> </p>
        <p> Preço: <input type="number" name="preco" step="10.00" required=""> </p>
        <p> Plataforma: <input type="text" name="plataforma" size=30 maxlength="30" required=""> </p>
        <p> Desenvolvedora: <input type="text" name="desenvolvedora" size=30 maxlength="30" required=""> </p>
        <p> <input type="submit" name="Atualizar" value="Atualizar jogo"> </p>
    </form>
  • If possible, try to be more objective and specific in your doubt. From what I understand, you don’t need this context

  • For my question not to be closed I had to bring as much information as possible of my doubt to people understand.

  • The information needs to be specific to the doubt. But come on, you want to select a select option with the label "Select Game" and the fields would be filled dynamically; that’s it?

  • @Leonardonegrão exactly, according to what is filled in the columns of a given game ID.

  • All right, I’ll try to help you

  • Dynamic fill also works for type fields <select>? I wanted to do it in the future.

  • Column-to-column Plataforma I wanted to put a <select> with a <option> with the options of PC, PS4 and Xbox One and make this dynamic fill in this <select>, for the <option> by default will always be empty.

Show 2 more comments

1 answer

0


To fill in the fields dynamically, that is, without reloading, you need to use javascript. And the first step is to better understand the DOM to correctly mark their respective fields, see the example below:

//solução com JQUERY
//detecta o manuseio do select
$(document).on('change','#cd_jogo',function(){
//coleta o resultado do select
valor = $(this).val();
//aqui você precisa fazer a requisição para coletar os resultados no seu backend em PHP e trazer um JSON parecido com o que está abaixo; você pode usar ajax (https://api.jquery.com/jquery.ajax/)
if(valor == 1) {
//o retorno do PHP precisa ser um objeto de JSON parecido com esse abaixo para preencher os campos
retornoPHP = '{ "nome":"Jogo1", "Preco":10, "Plataforma":"console", "Desenvolvedora": "desenvolvedora" }';
}
if(valor == 2) {
//o retorno do PHP precisa ser um objeto de JSON parecido com esse abaixo para preencher os campos
retornoPHP = '{ "nome":"Jogo2", "Preco":20, "Plataforma":"console", "Desenvolvedora": "desenvolvedora" }';
}
if(valor == 3) {
//o retorno do PHP precisa ser um objeto de JSON parecido com esse abaixo para preencher os campos
retornoPHP = '{ "nome":"Jogo3", "Preco":30, "Plataforma":"console", "Desenvolvedora": "desenvolvedora" }';
}
// Parse do json para você trabalhar os atributos separadamente
var obj = JSON.parse(retornoPHP);
//Adicionando os resultados aos respectivos campos
$('#nome').val(obj.nome);
$('#preco').val(obj.Preco);
$('#plataforma').val(obj.Plataforma);
$('#desenvolvedora').val(obj.Desenvolvedora);
//esse preenchimento é o "trazer automático"

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
        <p> Seleciona jogo:
        <select name="cd_jogo" id="cd_jogo" required="">
            <option value="1">1</option>  
            <option value="2">2</option>  
            <option value="3">3</option>  
        </select>
        </p>
        <p> Nome: <input type="text" name="nome" id="nome" size=30 maxlength="30" required=""> </p>
        <p> Preço: <input type="number" name="preco" id="preco" step="10.00" required=""> </p>
        <p> Plataforma: <input type="text" name="plataforma" id="plataforma" size=30 maxlength="30" required=""> </p>
        <p> Desenvolvedora: <input type="text" name="desenvolvedora"  id="desenvolvedora" size=30 maxlength="30" required=""> </p>
        <p> <input type="submit" name="Atualizar" value="Atualizar jogo"> </p>
    </form>

  • Notice that on the line echo "<option value='{$v['cd_jogo']}'>{$v['nome']}</option>"; is like an array with all keys in the table, whereas you specified in your Jquery the amount of keys, as I would change if(valor == 1) {&#xA;retornoPHP = '{ "nome":"Jogo1", "Preco":10, "Plataforma":"console", "Desenvolvedora": "desenvolvedora" }'; for my case? }

  • There is no problem that the fill is with backend data; the frontend always interpreted by the browser as HTML, CSS and JS. The point is that you need to get used to the concept of making asynchronous requests with Ajax

  • I have no knowledge of Ajax, so I’m learning Javascript

  • for your applications to have more life, JS is more important than PHP; as you can see in the example I showed, events work smoothly

  • I’m having trouble executing the code, like you set 3 <option> in the form and there is an if to test the existence of each <option> in JSON, but in my code I use the foreach to generate the id’s avoiding the use of both <option>, where I didn’t understand how to redo this part.

  • 1

    Other than that the code is good, just confused me a little because in the field of Seleciona jogo.

Show 1 more comment

Browser other questions tagged

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