php – How to add multiple phones to the same form dynamically?

Question:

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

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

For example, at least one contact phone number is required, so one field will appear by default, but my problem is 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 together with the data entered previously, without having to create a page to register phones for a specific user, one at a time.

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

To make sure I didn't forget any part of the code, I'll be making available all the project files, everything is very simple, as it only contains the registration system so far. MEGA

Anyway, from now on, I leave my thanks to those who help me.

Answer:

Well I made a quick example (better than completing your code and you don't 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 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 is the script , note the use of Ajax , it is what allows you to do this dynamic registration, in it I inform the method, the page where I will process my data, the data and also when I succeed etc.

3rd My INSERT with the cadastra.php page

<?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 the insert , so this is the one I quote in ajax . If everything works out, it will return to ajax the table row for my new record, if not, it returns a "fail" message


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

Scroll to Top