How to import database data into form field

Asked

Viewed 1,579 times

0

I have a course management system where the user has access to a table with all classes of all courses and chooses to enroll in a.

When the user is going to register, will open a form with the fields that he must fill and the field with the name of the formation and class, however, these fields I want to be already filled according to the formation and class of the row of the table that he clicked.

The query table:

<h1 style="
text-align: center;
height: 7;
margin-top: 150;
margin-bottom: 70
margin-top:130;
"> Consulta de turmas </h1>
<form method="post" action="selectT.php">
  <div class="col-lg-3">
    <div class="form-group">
      <label for="NOME">Nome: </label>
      <input class="form-control" id="NOME" placeholder="Nome da turma" name="NOME">
    </div>
  </div>
  <div class="col-lg-3">
    <div class="form-group">
      <label for="DATA">Data</label>
      <input class="form-control" id="DATA" placeholder="Data da formação" name="DATA">
    </div>
  </div>
  <div class="col-lg-3">
    <div class="form-group">
      <label for="LOCAL">Local: </label>
      <select class="form-control" id="LOCAL" name="LOCAL">
        <option>PR</option>
        <option>PL</option>
        <option>SP</option>
        <option>RJ</option>  
        <option>FR</option>
      </select>
    </div>
  </div>
  <button type="submit" class="btn btn-primary" style="margin-top: 22;">Buscar</button>
</form>

<?php
//Conexão e consulta ao Mysql
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('db_formacao') or die(mysql_error());
$qry = mysql_query("select * from turmas");

//Pegando os nomes dos campos
$num_fields = mysql_num_fields($qry);//Obtém o número de campos do resultado

for($i = 0;$i<$num_fields; $i++){//Pega o nome dos campos
  $fields[] = mysql_field_name($qry,$i);
}

//Montando o cabeçalho da tabela
$table = '<table class="table table-hover table-inverse" style="margin-top:50;background-color: #37444a; color:lightgrey;"> <tr>';

for($i = 0;$i < $num_fields; $i++){
  $table .= '<th>'.$fields[$i].'</th>';
}

//Montando o corpo da tabela
$table .= '<tbody style="
  background-color: #86979e;
  color: #37444a;    
">';
while($r = mysql_fetch_array($qry)){
  $table .= '<tr>';
  for($i = 0;$i < $num_fields; $i++){
    $table .= '<td>'.$r[$fields[$i]].'</td>';
  }

  // Adicionando botão de exclusão
  $table .= '<td><form action="inscricao.php" method="post">'; //formulário com método post que vai para deleteF.php
  $table .= '<input type="hidden" name="ID" value="'.$r['ID'].'">';
  $table .= '<button class="btn btn-primary">Inscreva-se</button>'; //aqui está o seu botão
  $table .= '</form></td>';
}

//Finalizando a tabela
$table .= '</tbody></table>';

//Imprimindo a tabela
echo $table;

?>

The application form:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_formacao";

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT NOME FROM turmas";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    $row = $result->fetch_assoc(); 
}
?>

<div class="container">
    <div class="row">
        <div class="col-lg-12 text-center">
            <h1 style="
                margin-top:100px;">Inscrição</h1>
            <p> </p>
            <p class="lead"></p>
            <ul class="list-unstyled">
                <form id="cadastro" method="post" action="banco/updateP.php" style="
                    text-align: left;
                    margin-top:50px;">
                    <div class="col-lg-12">
                        <div class="form-group" style="
                    text-align: left;">
                            <label  for="FORMACAO">Formação: </label>
                            <input  type="text" required class="form-control" id="FORMACAO" name="FORMACAO" value="<?=$row['nome']?>">
                         </div>
                    </div>
                    <div class="col-lg-12">
                        <div class="form-group" method="post" style="
                    text-align: left;">
                            <label  for="TURMA">Turma: </label>
                            <input  type="text" required class="form-control" id="TURMA" name="TURMA">
                         </div>
                    </div>
                    <div class="col-lg-12">
                        <div class="form-group" method="post" style="
                    text-align: left;">
                            <label  for="COLABORADOR">Colaborador: </label>
                            <select  class="form-control" id="COLABORADOR" name="COLABORADOR">
                                <?php

                                ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-lg-12">
                        <div class="form-group" method="post" style="
                    text-align: left;">
                            <label  for="PREVISTO">Status: </label>
                            <input  type="text" required class="form-control" id="PREVISTO" name="PREVISTO" value="Previsto">
                         </div>
                        <div class="form-check form-check-inline disabled">
                            <label class="form-check-label">
                                <input class="form-check-input" type="radio" name="STATUS" id="STATUS" value="Realizado" disabled> Realizado
                            </label>
                        </div>
                        <div class="">
                            <button type="submit" class="btn btn-primary btn-lg btn-block">Salvar</button>
                        </div>
                    </div>
                </form>
            </ul>
        </div>
    </div>
</div> 

The consultation:

inserir a descrição da imagem aqui

The form:

inserir a descrição da imagem aqui

  • because almost all people still use mysql_*? should redo for PDO or Mysqli or if not your site is exposed to various types of attacks...

  • I use an old version of php and can not change because there are many systems running in this version.

  • what is the php version ?

  • The version is php 5.2.10

2 answers

3

To set an initial value to form fields, you follow these patterns:

For input text, email, password, etc.

Sets the value by the attribute value. Example:

<input type="text" name="nome" value="João da Silva">

For checkbox and radio inputs:

Defines the attribute checked for what needs to be marked. Example:

<input type="radio" name="sexo" value="Masculino" checked="checked">
<input type="radio" name="sexo" value="Feminino">

For textarea:

Just put the content inside the tag. Example:

<textarea name="mensagem">Lorem ipsun sit dolor omet</textarea>

To select:

Defines the attribute selected for the option that should already be selected, example:

<select name="cidade">
    <option value="Rio de Janeiro">Rio de Janeiro</option>
    <option value="São Paulo" selected="selected">São Paulo</option>
    <option value="Curitiba">Curitiba</option>
</select>

Follow an example form now:

body {
  font-family: sans-serif;
}
label {
  display: block;
}
.radio-group {
  display: block;
}
.radio-group label {
  display: inline;
}
<form>
  <p>
    <label for="nome">Nome:</label>
    <input type="text" id="nome" name="nome" value="João da Silva">
  </p>
  <p>
    <label>Sexo:</label>
    <span class="radio-group">
      <input type="radio" id="masculino" name="sexo" value="Masculino" checked="checked">
      <label for="masculino">Masculino</label>
      <input type="radio" id="feminino" name="sexo" value="Feminino">
      <label for="feminino">Feminino</label>
    </span>
  </p>
  <p>
    <label for="mensagem">Mensagem:</label>
    <textarea id="mensagem" name="mensagem">Lorem ipsun sit dolor omet</textarea>
  </p>
  <p>
    <label for="cidade">Cidade:</label>
    <select id="cidade" name="cidade">
        <option value="Rio de Janeiro">Rio de Janeiro</option>
        <option value="São Paulo" selected="selected">São Paulo</option>
        <option value="Curitiba">Curitiba</option>
    </select>
  </p>
  <p>
    <input type="submit" value="Enviar">
  </p>
</form>

Example bringing Mysql values by PHP:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT nome, sexo, mensagem, cidade FROM pessoas WHERE id_pessoa = 10;";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    $row = $result->fetch_assoc();

    ?>
        <form>
            <p>
                <label for="nome">Nome:</label>
                <input type="text" id="nome" name="nome" value="<?=$row['nome']?>">
            </p>
            <p>
                <label>Sexo:</label>
                <span class="radio-group">
                    <input type="radio" id="masculino" name="sexo" value="Masculino"<?php if($row['sexo'] == 'Masculino') { echo ' checked="checked"'; } ?>>
                    <label for="masculino">Masculino</label>
                    <input type="radio" id="feminino" name="sexo" value="Feminino"<?php if($row['sexo'] == 'Feminino') { echo ' checked="checked"'; } ?>>
                    <label for="feminino">Feminino</label>
                </span>
            </p>
            <p>
                <label for="mensagem">Mensagem:</label>
                <textarea id="mensagem" name="mensagem"><?=$row['nome']?></textarea>
            </p>
            <p>
                <label for="cidade">Cidade:</label>
                <select id="cidade" name="cidade">
                    <option value="Rio de Janeiro"<?php if($row['cidade'] == 'Rio de Janeiro') { echo ' checked="checked"'; } ?>>Rio de Janeiro</option>
                    <option value="São Paulo"<?php if($row['cidade'] == 'São Paulo') { echo ' checked="checked"'; } ?>>São Paulo</option>
                    <option value="Curitiba"<?php if($row['cidade'] == 'Curitiba') { echo ' checked="checked"'; } ?>>Curitiba</option>
                </select>
            </p>
            <p>
                <input type="submit" value="Enviar">
            </p>
        </form>
    <?php
} else {
    echo "0 results";
}
$conn->close();
?>
  • Your reply was very helpful, however, I want what is in that value to be taken from the database.

  • I tried to put value="<? php echo $name['NAME']? >" but I must have to specify the table and make the connection to database, right?

  • exact, in this case need first connect with the bank, recover the values and then print at the value exactly as you put

  • 1

    I added an example with data brought from Mysql by PHP

  • So I copied your code and adapted it to mine, but without Else because it wasn’t working; it still doesn’t work. I’ll edit my question, if I can, you can show me where I’m missing?

  • We’ll help any way we can

  • Aaaah, thank you! You are very careful with the answers, you should be a teacher.

Show 3 more comments

1


In the query table, in this section

.......................
.......................
//Montando o corpo da tabela
$table .= '<tbody style="
  background-color: #86979e;
  color: #37444a;    
">';

$table .= '<form action="inscricao.php" method="post">'; //formulário com método post que vai para deleteF.php

while($r = mysql_fetch_array($qry)){

  $table .= '<tr>';

  for($i = 0;$i < $num_fields; $i++){
    $table .= '<td>'.$r[$fields[$i]].'</td>';
  }

  // Adicionando botão de exclusão
      $table .= '<td><input type="hidden" name="ID" value="'.$r['ID'].'">';
      //$table .= "<td><input type=\"hidden\" name=\"ID\" value=\"".$r["ID"]."\">";
      $table .= '<button type="submit" class="btn btn-primary">Inscreva-se</button> </td>'; //aqui está o seu botão

  $table .= '</tr>';
}
$table .= '</form>';

//Finalizando a tabela
$table .= '</tbody></table>';

//Imprimindo a tabela
echo $table;

the changes were:

  1. structure of the form, lines (tr and td) of the table
  2. specify the type of button <button type="submit"

About the type attribute of Buttons

  1. Submit: The button sends the form data to the server.
  2. button: The button has no default behavior. It may have client-side scripts associated with element events, in which they are triggered when the event occurs.

<button> - Mozilla Developer Network

And on the application form:

 ................
 $id=$_POST["ID"];
 $sql = "SELECT ID,NOME FROM turmas where ID='$id'";
 $result = $conn->query($sql);
 ................
 ................
 <label  for="TURMA">Turma: </label>
 <input  type="text" required class="form-control" id="TURMA" name="TURMA" value="<?=$row['ID'] ?>">

Browser other questions tagged

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