How to send form data to mysql?

Asked

Viewed 691 times

1

inserir a descrição da imagem aqui

I am trying to send the form data to mysql but give error Notice:

Array to string Conversion in C: xampp htdocs Requested projects.php on line 16

The line 16 is this

$sql="INSERT INTO spedido(numero_mesa,pedido,quantidade) VALUES('$numero_mesa','$pedido','$quantidade')";

and when send it only takes the table and one of select, the quantity does not take . what would be giving this error ?

 <?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_refeicao = $_POST['pedido_refeicao'];
    $num_refeicao = $_POST['num_refeicao'];
    $pedido_bebida = $_POST['edido_bebida'];
    $num_bebida = $_POST['num_bebida'];
        $sql="INSERT INTO npedido(numero_mesa,pedido_refeicao,num_refeicao,pedido_bebida,num_bebida) VALUES('$numero_mesa','$pedido_refeicao','$num_refeicao','$pedido_bebida','$num_bebida')";
        $resultado_pedido = mysqli_query($link,$sql);
}
?>
<!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 method="post" action="pedidos.php">
            <header>
                <h2>Fazer Pedido</h2>
            </header>
            <fieldset>
                <label>
                    <span>Mesa</span>
                    <input type="text"id="numero_mesa" name="numero_mesa">
                </label>
                <label>
                    <span>Comanda:</span>

                </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  class="pedidos">

                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                    <select name="pedido" id="pedido"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>
<br>
<button class="btn" type="submit">Fazer Pedido</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>
  • You are trying to pass a request with multiple items, correct? And if you can, highlight line 16 of the php part of the code.

  • @Renefreak yes are the meals and quantities , and drinks and quantities . I will update the question.

  • @allanaraujo what returns if you add before this line the command echo "quantidade: ".count($quantidade);?

  • @Leocaracciolo where I can get this source code ?

  • the source code can pick up the page itself before doing qq Submit

  • the php part I will post an answer as soon as I get back

  • ok but it goes to the database right ?

  • yes has Insert and when reuse a table makes a delete

  • This way is even faster than a select right after all I will use on a tablet .

Show 4 more comments

4 answers

2


You have to validate the data, do some checks and so on... quite a task :)

this php puts right at the beginning of the page

<?php

if (isset($_POST["pedido"])) {

$link = new mysqli ("localhost", "USUARIO", "SENHA", "DB");
if($link->connect_errno){
echo"Nossas falhas local experiência ..";
exit();
}

$sql = ("DELETE FROM spedido Where numero_mesa='".$numero_mesa."'");
$resultado_pedido = mysqli_query($link,$sql);

$numero_mesa=$_POST["numero_mesa"];
$optionArray = $_POST["pedido"];

for ($i = 0; $i < count($optionArray); $i++) {
$pedido=$pedido.",".$optionArray[$i];
$pedido=str_replace(",,",",",$pedido);
}
$pedido=substr($pedido, 1,(strlen($pedido)-2));

$aDest = explode(",", $pedido);
$result = count($aDest);

for ($k = 0; $k < $result; $k++) {
$par = $aDest[$k];
if ($k%2==0){
$pedido=$par;
$alerta = $alerta.$par.": ";
}else{
$quantidade=$par;
$sql = "INSERT INTO spedido(numero_mesa,pedido,quantidade) VALUES('$numero_mesa','$pedido','$quantidade')";
$resultado_pedido = mysqli_query($link,$sql);
$alerta = $alerta.$par."<br>";
}
}

echo ("<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script>
<script type=\"text/javascript\" src=\"http://www.jacklmoore.com/colorbox/jquery.colorbox.js\"></script>
<link rel=\"stylesheet\" type=\"text/css\" href=\"http://www.jacklmoore.com/colorbox/example1/colorbox.css\">");

if ($alerta != ""){
$res=$result*15;
if ($res<80){
$res=80;
}
echo ("<style>#ajax{height:".$res."px; width:500px;}</style>
<script type=\"text/javascript\">
$(window).load(function(){
$(document).ready(function(){
$.colorbox({inline:true, href:\".ajax\"});
});
});

function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>");
echo ("<div style=\"display:none\"><div id=\"ajax\" class=\"ajax\">Pedido mesa: 
".$numero_mesa."<br><ul>".$alerta."</ul><input type=\"button\" onclick=\"printDiv('ajax')\" 
value=\"Imprimir\" /></div></div>"); 

}
}
?>

  • Added function Print floating window contents by Kevin Florida http://stackoverflow.com/questions/468881/print-div-printarea-div-only Table number validation has also been added. So copy the source code from the page before doing qq Submit

0

You should use a master-detail data model.

At least two tables.

One is master of the order: number, table, hour, waiter, etc. and the other with the details, which are the items: product, Qtd, price, etc.

The error occurs because you are trying to pass an array (many values) as a string (a value).

0

Array to string conversion is an error that happens when the programmer uses an array when PHP expects a string. Since PHP doesn’t know how to turn this array into a string, it launches the error.

$sql = "INSERT INTO spedido(numero_table,request,quantity) VALUES('$numero_mesa','$pedido','$quantidade')";

That said, $numero_mesa, $pedido and/or $quantidade are arrays. You must process this data before using it in the queries.

  • @fernadosavio how it could treat these data ?

  • First you need to know what an array and string is. Once this is done you need to know what you receive from the form, if it is an array with several values you probably want to do several Inserts. Second, you need to learn how to avoid SQL Injection using Prepared statements of mysqli (or PDO).

  • how could put in the form the columns num_refeicao num_bebida , and the part that is to add the amount is in javascript ?

0

A quick solution would be to create in the table

numero_mesa
pedido_refeicao  ** para os pedido da refeição
num_refeicao     ** lista a quantidade de refeição
pedido_bebida    ** lista as bebidas
num_bebida       ** Lista a Quantidade de Bebidas

then saves everything to in the table and then only lists the removal

  • I’ll do it Leo

  • I already did but how can I insert with the form I put in the question , and that has a part that is in javascript ?

  • where you have <input type='text' name='quantity[]' placeholder='quantity'> you will increment with the names of the fields you create. and put tbm on the send part to the bank.

  • in my case I didn’t use the same I used Chosen to mark the options I would have and put the others to select manually. see: http://quetalumapizza.esy.es/compras_teste.php

  • if I input javascript it loses the add function .

Browser other questions tagged

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