how to insert data into two tables at the same time

Asked

Viewed 1,197 times

0

I wonder how I can do to insert data into two tables at the same time , well I do not know if it is right the way I am doing it is not giving any error but also did not insert anything .

The code below.

<?php
error_reporting(-1);
ini_set('display_errors', 'On');

//Criar a conexao
$link = new mysqli ("localhost", "root", "", "peixaria");
if($link->connect_errno){
     echo"Nossas falhas local experiência ..";
     exit();
}

if($_SERVER['REQUEST_METHOD'] == 'POST') {
        $numero_mesa = $_POST['numero_mesa'];
    $pedido = $_POST['pedido'];
    $quantidade = $_POST['quantidade'];

    //echo "$nome_usuario - $email_usuario";

    //echo "<pre>"; print_r($_POST); exit;

    $query1 = "INSERT INTO pedido (mesa) VALUES ('$numero_mesa')";
   mysqli_query( $query1 );

    $id = mysqli_insert_id();

    $query2 = "INSERT INTO item_pedido (pedido,quantidade) VALUES ({$id}, '$pedido', '$quantidade')";
    mysqli_query( $query2 );

}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Peixaria</title>
    <style>
        .add {
            text - decoration: none;
        }
    </style>
</head>
<body>
<style>
.add,add2{ text-decoration:none;}
#selecionados input,#selecionados2 input{ margin:10px;}
</style>
    <h1>Peixaria</h1>
    <ul class="menu cf">
        <li><a href="secao.php">Início</a></li>
        <li><a href="pedidos.php">Pedidos</a></li>
        <li><a href="reserva.php">Reserva</a></li>
        <li><a href="relatorio.php">Relatório</a></li>
    </ul>
    <main>
        <form>
            <header>
                <h2>Fazer Pedido</h2>
            </header>
            <fieldset>
                <label>
                    <span>Comanda:</span>
                    <input type="text">
                </label>
                <label>
                    <span>Mesa:</span>
                    <input type="text" id="numero_mesa" name="numero_mesa">
                </label>
                <span>Refeições/Bebidas/Sobremesas:</span>
                <div class="pedidos">

                    <select name="pedido,quantidade" id="pedido,quantidade"class="selecionar">
                        <option selected disabled>Selecione</option>
                        <option >Costela de Tambaqui sem Espinha</option> 
                        <option  >Lombo de Tambaqui Frito sem Espinha</option>
                        <option >Caldeirada de Tambaqui sem Espinha</option>
                        <option >Caldeirada de Tucunaré</option> 
                        <option >Peixe no Tucupi com Camarão</option>
                        <option >Escabeche de Pirarucu</option>
                        <option >Escabeche de Tambaqui</option>
                        <option >Escabeche de Tucunaré</option>
                        <option >Tucunaré Frito</option> 
                        <option >Sardinha Frita</option>
                        <option >Jaraqui Frito</option>
                        <option >Pacu Frito</option> 
                        <option >Filé de Pirarucu Frito</option>
                        <option >Filé de Pirarucu a Milanesa</option>
                        <option >Guisado de Pirarucu</option>
                    </select>
                    <a class="add" href="#">+</a>
                    <hr>
                    Selecionados
                    <hr>
                    <div class="selecionados">

                    </div>
                </div>
               <br>
                <div name="pedido,quantidade" id="pedido,quantidade" class="pedidos">

                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                    <select class="selecionar">
                        <option selected disabled>Selecione</option> 
                        <option >Fanta Laranja 1l</option> 
                        <option >Fanta Laranja 2l</option> 
                        <option >Cola Cola 1l</option>
                        <option >Cola Cola 2l</option>
                        <option >Bare 2l</option> 
                        <option >Fanta Uva</option>
                        <option >Fanta Laranja</option>
                        <option >Sprit</option> 
                        <option >Cola Cola </option>
                        <option >Cola Cola zero </option>
                        <option >Guaraná Antarctica</option> 
                        <option >Guaraná Baré</option>
                        <option >Suco Goiaba</option> 
                        <option >Suco Manga</option>
                        <option >Suco Pessego</option>
                        <option >Suco Uva</option> 
                        <option >Suco Maracujá</option>
                        <option >Suco Laranja</option>
                        <option >Suco Caju</option> 
                        <option >Agua Mineral </option>
                        <option >Agua com Gas </option>
                        <option >Cerveja em Lata</option> 
                        <option >Limonada Natural</option>
                    </select>
                    <a class="add" href="#">+</a>
                    <hr>
                    Selecionados
                    <hr>
                    <div class="selecionados">

                    </div>

                </div>
<b>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>   
            </fieldset>

        </form>
    </main>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>

        $(".add").on('click',function(){ 
            var cont=0;
            var holder = $(this).closest('.pedidos');
            holder.find(".selecionados input").each(function(){
                if($(this).val()==holder.find(".selecionar option:selected").html()){
                    cont++;
                }
            });
            if(cont>0) { 
                alert("Este item ja esta adicionado, altere a quantidade se deseja mais..");
            } else{
                holder.find(".selecionados").append(
                    "<input disabled type='text' name='pedidos[]' value='" + 
                    holder.find(".selecionar option:selected").html() + 
                    "' ><input type='text' name='quantidade[]' placeholder='quantidade'><br>"
                );
            }
        });


    </script>

2 answers

1


The problem is similar to what I answered this question. The difference is you’re not using procedural mode, but come on.

First you create the connection:

$link = new mysqli ("localhost", "root", "", "peixaria");

If the credentials are correct there is no error, so the $link is the one who has access to the Mysqli class and has access to Mysql.

Now you need to use:

$link->funcao();

This is because it is the $link with the Mysqli class, so in order to be able to use the functions, you must use:

$link->query($query1);

This applies to all functions, for example:

$link->insert_id;

Not all Mysqli functions will use $link.

I can not technically explain, but you want to get the result of a want for example use the mysqli_fetch_array, you must use the variable that has the result.

For example:

$link = new mysqli ("localhost", "root", "", "teste");
$resultado = $link->query('SELECT * FROM tabela WHERE id = 1');

$resultado->fetch_row();

You should not use $link->fetch_row(), an easy way to see what you need to see in the documentation, it says exactly who should be called. ;)

I guess you figured out the logic.

  • more or less but , where would really be the error in my code being that there is no error but also insert nothing in the bd

0

You forgot to pass all the necessary parameters to the function mysqli_query.

Change these lines:

mysqli_query( $query1 );
mysqli_query( $query2 );

To:

mysqli_query($link, $query1);
mysqli_query($link, $query2);
  • even putting the link does not appear anything in the database when the form is sent .

  • try to remove value {$id} and leave only: INSERT INTO item_pedido (pedido,quantidade) VALUES ('$pedido', '$quantidade');

  • Even so I think there’s another mistake besides the one that’s not working.

  • Also check that $numero_mesa,$pedido and $quantidade are not empty. Because I tested here without checking the REQUEST_METHOD and inserted normal.

  • would have as it says what you tested

  • Here’s the code, of course, I changed the information on banco de dados, tabela and colunas. Link: http://pastebin.com/zuzMReRJ

Show 1 more comment

Browser other questions tagged

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