Insert data into different tables

Asked

Viewed 32 times

1

I have a form with action for this script and POST method, and some values need to be inserted in different tables of the database, but either just insert in a table, or do not insert in any.

<?php

if($_POST["acao"] == "inserir"){
        inserirCliente();
}

function inserirCliente(){
    $bd = new mysqli("localhost", "root", "", "projeto_ap2" );
    $sql = "INSERT INTO cliente(cpf, nome, dt_nasc) "
                . "VALUES ('{$_POST["cpfCliente"]}','{$_POST["nomeCliente"]}','{$_POST["dataNascimentoCliente"]}')";

            "INSERT INTO cliente_endereco(cpf_cliente, cep, cidade, estado, bairro, logradouro, numero)"
                . "VALUES ('{$_POST["cpfCliente"]}','{$_POST["cepCliente"]}','{$_POST["cidadeCliente"]}','{$_POST["estadoCliente"]}','{$_POST["bairroCliente"]}','{$_POST["logradouroCliente"]}','{$_POST["numeroCasaCliente"]}')";

            "INSERT INTO cliente_telefone(cpf_cliente, telefone_cliente)"
                . "VALUES ('{$_POST["cpfCliente"]}','{$_POST["telefoneCliente"]}')";

    $bd->query($sql);
    $bd->close();
}

header("Location: index.php");
  • already tried to separate the three queries into three variables and then execute them?

1 answer

2

If I remember correctly, you can only run one query at a time on mysqli same, but what’s the problem in running one at a time?

$sql1 = "INSERT INTO cliente(cpf, nome, dt_nasc) "
            . "VALUES ('{$_POST["cpfCliente"]}','{$_POST["nomeCliente"]}','{$_POST["dataNascimentoCliente"]}')";

$sql2 = "INSERT INTO cliente_endereco(cpf_cliente, cep, cidade, estado, bairro, logradouro, numero)"
            . "VALUES ('{$_POST["cpfCliente"]}','{$_POST["cepCliente"]}','{$_POST["cidadeCliente"]}','{$_POST["estadoCliente"]}','{$_POST["bairroCliente"]}','{$_POST["logradouroCliente"]}','{$_POST["numeroCasaCliente"]}')";

$sql3 = "INSERT INTO cliente_telefone(cpf_cliente, telefone_cliente)"
            . "VALUES ('{$_POST["cpfCliente"]}','{$_POST["telefoneCliente"]}')";

$bd->query($sql1);
$bd->query($sql2);
$bd->query($sql3);
$bd->close();
  • sql3 has not been saved, but the POST data is correct

  • @Lucas, check the table cliente_telefone or columns cpf_cliente and telefone_cliente are under the same name in the database?

  • Yes, they have the same name. It’s all right, I just don’t understand why you didn’t enter

  • @Lucas, both CPF and Phone are set to type VARCHAR or some variation of string? There must be something wrong, either in the query, or in the database.

  • It worked here. CPF and Phone were set to int, but the number is technically large dms for integer. I switched to BIGINT and it worked. Thank you for your attention.

  • @Lucas, CPF can start with the number 0, if you set it as a numeric type you will lose the zeros on the left.

Show 1 more comment

Browser other questions tagged

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