Insert into two separate tables

Asked

Viewed 653 times

-1

I have two tables (cliente and telefone), I need to insert the name in the table cliente and the customer’s phone in the table telefone, at the same time, by the same form.

In the HTML form I managed to put all fields (name, ddd, phone) but I can’t send to both tables.

if(isset($_POST['nome'])){
    $nome = filter_input(INPUT_POST,'nome',FILTER_SANITIZE_STRING);
    $ddd = filter_input(INPUT_POST,'ddd',FILTER_SANITIZE_STRING);
    $telefone = filter_input(INPUT_POST,'telefone',FILTER_SANITIZE_STRING);    

    $solicita = "INSERT INTO `cliente` (`nome`) VALUES ($nome),
                 INSERT INTO `telefone` (`ddd`,`telefone`) VALUES ($ddd,$telefone)";
    $query = mysqli_query($conn,$solicita);

    if($linha_usuario = mysqli_insert_id($conn)){  
    echo "Cadastrado com sucesso";
    }else{
        echo "Erro ao cadastrar";
    }
}
?>

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Desafio Estágio</title>
    <link rel="stylesheet" href="estilo.css">
</head>

<body>
    <h1>Cadastro de clientes</h1>
    <form action="index.php" method="post" id="form">
        <label for="nome">Nome</label>
        <input type="text" id="nome" name="nome">
        <label for="ddd">D.D.D</label>
        <input type="text" id="ddd" name="ddd" size="2">
        <label for="telefone">Telefone</label>
        <input type="text" id="telefone" name="telefone">
        <input type="submit" value="Cadastrar" id="cadastrar">
    </form>

</body>

</html>

Diagrama de classe

  • Good morning, please add the code with what you tried to send to be able to help you

  • Hello Osiris put the code, thanks for your help

  • Error appears or simply does not insert?

  • Do not register in any database, I tried to put only the name in the client table and it worked but when I try to register in the other table will not. In no table

  • Hello! You can solve it by running queries one by one. Or you can try using mysqli.multi-query

1 answer

-1

I believe the error happens because the client’s FK field in the phone table is not in your second input, fields are missing. Divide the 2 Inserts and before entering the phone try to do what I did below.

$sql = select * from cliente where like '%$nome%';
$consulta = mysqli_query($conn,$sql);
while($linha = mysqli_fetch_array($consulta)){

$id = $linha['id'];
}

if($id == TRUE) {

$sqlTelefone = 'insert into telefone (cliente_id, ddd, telefone) values ($id,$ddd,$telefone)';
$resultado = mysqli_query($conn,$sqlTelefone);

}

Dude, I did it in my head, there might be a syntax error, but anything leaves a comment. Hug!

Browser other questions tagged

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