How do I add multiple phones to the same form dynamically?

3

I'm studying PHP and SQL and I'm building a system so that my mother can better manage all the clients who use the transport service she provides.

I built a simple registration page with the necessary information, and would like to update it to add contact phones dynamically.

For example, at least one contact phone is required, so a field will appear by default, but my problem is with adding more phones through the same form, as I would like to put a "+" button to add another field and register this in the database along with the previously entered data, without having to create a page to register phones to a specific user, one at a time.

I imagine this requires the use of JS , however I really have no idea how to start implementing it on the registration page. I can not figure out what the SQL and PHP would look like.

To make sure I have not forgotten any part of the code, I'll be making all the project files available, it's all very simple, because it only contains the registration system so far. MEGA

Anyway, I would like to thank all those who help me.

    
asked by anonymous 01.02.2016 / 17:51

1 answer

1

Well I did a quick example (rather than completing your code and you do not understand).

1st I have a telefone table with id , nome and telefone :

--
-- Database: 'sistema'
--
CREATE DATABASE IF NOT EXISTS 'sistema';
USE 'sistema';

--
-- Estrutura da tabela 'telefone'
--

CREATE TABLE IF NOT EXISTS 'telefone' (
  'id' int(11) NOT NULL AUTO_INCREMENT,
  'nome' varchar(255) NOT NULL,
  'telefone' varchar(15) NOT NULL,
  PRIMARY KEY ('id')
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

--
-- Extraindo dados da tabela 'telefone'
--

INSERT INTO 'telefone' ('id', 'nome', 'telefone') VALUES
(1, 'Stack', '1111111111111'),
(2, 'Over', '22222222222222'),
(3, 'Flow', '333333333');

2nd I set up my registration page (I used jquery and bootstrap ):

<?php
require_once 'minpdo.php'; //importo minha biblioteca de crud
require_once 'telefone.php'; //php com definições do meu banco e tabela

$mnpdo = new MinPDO();
try {
    $telefones = $mnpdo->consult("telefone", "*"); // consulta todos telefones
} catch (MinPDOException $ex) { //caso haja erro
    echo <<<ERRO
    <div class="text-center text-danger">
    {$ex->getMessage()}
    </div>
ERRO;
}


?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Cadastro dinâmico</title>

        <link rel="stylesheet" href="bootstrap.css" />
    </head>
    <body>
        <table class="table table-hover" id="telefones">
            <tr class="text-primary">
                <td colspan="2">
                    <strong>Nome</strong>
                </td>
                <td>
                    <strong>Telefone</strong>
                </td>
            </tr>

        <?php 
        if(!empty($telefones)) { // se tiver telefones
            for($i = 0; $i < count($telefones); $i ++) { //exibe todos
                echo <<<ITEM
            <tr>
                <td colspan="2">
                    <p>{$telefones[$i]['nome']}</p>
                </td>
                <td>
                    <p>{$telefones[$i]['telefone']}</p>
                </td>
            </tr>
ITEM;
            }
        }
        ?>
        </table>
        <table class="table table-striped">
            <tr class="text-center">
                <td>
                    <br>
                    <div class="form-group">
                        <label>Nome:</label>
                        <input name="nome" class="form-control" id="nome" type="text" />
                    </div>
                </td>
                <td>
                    <br>
                    <div class="form-group">
                        <label>Telefone:</label>
                        <input name="telefone" maxlength="15" class="form-control" id="telefone" type="tel" />
                    </div>
                </td>
                <td>
                    <br>
                    <div class="form-group">
                        <label style="opacity: 0;">...</label>
                        <input class="btn btn-primary form-control envia" value="+" type="submit" />
                    </div>
                </td>
            </tr>
        </table>
        <script src="jquery.js"></script>

        <script>
        $(function(){
            $(".envia").click(function() {
                if( $('#nome').val() != "" && $('#telefone').val() ) { //se ambos tiverem com conteudo
                    $.ajax({
                        type: "POST", //tipo de registro
                        url: "cadastra.php", //pagina de cadastro
                        data: { //envia nome e telefone
                            nome : $("#nome").val(),
                            telefone : $("#telefone").val()
                        } ,
                        success: function(retorno) {
                            if(retorno == "fail") {
                                //falha
                            } else {
                                $("table#telefones tr:last").after(retorno); //exibe novo registro
                            }
                        }
                    });
                }
            });
        });
        </script>
    </body>

</html>

The most important part here is script , note the use of Ajax , it is the one that allows to make this dynamic register, it informs the method, the page where I will treat my data, the data and also when success etc.

3rd My INSERT with the page cadastra.php

<?php
require_once 'minpdo.php';
require_once 'telefone.php';

$mnpdo = new MinPDO();
if(isset($_POST['nome']) and isset($_POST['telefone'])) {
    try { //tenta inserir e dar echo (retorno do ajax) de uma linha da tabela
        $mnpdo->insert("telefone",
            array("nome", "telefone"),
            array($_POST['nome'], $_POST['telefone']) );

        echo <<<ITEM
            <tr>
                <td colspan="2">
                    <p>{$_POST['nome']}</p>
                </td>
                <td>
                    <p>{$_POST['telefone']}</p>
                </td>
            </tr>
ITEM;
    } catch (MinPDOException $ex) {
        echo "fail"; // falha do bd
    }
} else {
    echo "fail"; // não tem dados
}

Note that this is the page that does insert , so it's the one that I am quoting in ajax . If it works fine, it will return to ajax the table row for my new record, if not, it returns a message "fail"

The example can be downloaded in this MEGA link , to test, run the sistema.sql file on your data manager, and enter index.php . The file minpdo.php is a class I made CRUD to help my projects, if I have interest in this GitHub link there is the tutorial on how to use it.

    
01.02.2016 / 21:50