I’m having trouble with Undefined index

Asked

Viewed 110 times

0

 <?php 
$con = "";

function Conectar(){
$servidor = "localhost";
$usuario = "root";
$senha = "usbw";
$banco = "localcar";
$GLOBALS['con'] = new mysqli($servidor,$usuario,$senha,$banco);
}

//chamamos a função aqui para toda vez que fizermos include a conexão ser feita automaticamente..
Conectar();

function CadastrarCliente($nome,$cnh,$endereco){

    //comando da linguagem sql (do banco de dados mysql) para inserção de dados na tabela cliente
    $sql = 'INSERT INTO cliente VALUES (null,"'.$nome.'","'.$cnh.'","'.$endereco.'")';

    $res = $GLOBALS['con']->query($sql);
        if($res){
        //caso o comando seja executado sem problema, exibimos a mensagem abaixo
            alert("Cliente Cadastrado");
        }
}
function CadastrarVeiculo($placa,$modelo,$cor,$ano,$qntd_passageiro){

    //comando da linguagem sql (do banco de dados mysql) para inserção de dados na tabela veiculo
    $sql = 'INSERT INTO veiculo VALUES (null,"'.$placa.'","'.$modelo.'","'.$cor.'","'.$ano.'","'.$qntd_passageiro.'")';

    $res = $GLOBALS['con']->query($sql);
        if($res){
        //caso o comando seja executado sem problema, exibimos a mensagem abaixo
            alert("Veiculo Cadastrado");
        }
}
function alert($msg){
    echo '<script> alert("'.$msg.'");</script>';
}
function MostrarCliente(){
    //comando para listar todas os clientes
    $sql = 'SELECT * FROM cliente LIMIT 0,4';
    //executando comando no banco
    $resultado = $GLOBALS['con']->query($sql);
    //verificando se existem clientes cadastrados
    if($resultado->num_rows > 0){
        //enquanto houver clientes, iremos mostrar
        while($cliente = $resultado->fetch_array()){
            //como será exibido (codigo html embutido)
            echo '<div class="row">
                    <div class="col-md-8 col-md-offset-2">
                      <p>Nome: '.$cliente['nome'].'</p>
                      <p>CNH: '.$cliente['cnh'].'</p>
                      <p>Endereco: '.$cliente['endereco'].'</p>
                    </div> 
                  </div>';
        }
    }else{
        //nao tem Clientes
    }
}
function MostrarVeiculo(){
    //comando para listar todos os veiculos
    $sql = 'SELECT * FROM veiculo LIMIT 0,4';
    //executando comando no banco
    $resultado = $GLOBALS['con']->query($sql);
    //verificando se existem veiculos cadastrados
    if($resultado->num_rows > 0){
        //enquanto houver veiculos, iremos mostrar
        while($veiculo = $resultado->fetch_array()){
            //como será exibido (codigo html embutido)
            echo '<div class="row">
                    <div class="col-md-8 col-md-offset-2">
                      <p>Placa: '.$veiculo['placa'].'</p>
                      <p>Modelo: '.$veiculo['modelo'].'</p>
                      <p>Cor: '.$veiculo['cor'].'</p>
                      <p>Ano: '.$veiculo['ano'].'</p>
                      <p>Quantidade de Passageiros: '.$veiculo['qntd_passageiro'].'</p>
                    </div> 
                  </div>';
        }
    }else{
        //nao tem Veiculos
    }
}
?>

`

<?php 
include("funcoes.php");
if($_POST){
    CadastrarCliente($_POST['id'], $_POST['nome'],$_POST['cnh'],$_POST['endereco']);
CadastrarVeiculo($_POST['placa'],$_POST['modelo'],$_POST['cor'],$_POST['ano'],$_POST['qntd_passageiro']);
}
?>
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link href="../css/style.css" rel="stylesheet">
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/scripts.js"></script>
<meta charset="utf-8">

<script type="text/javascript">
  $(document).ready(function(){
    $('#cliente').click(function(){
      $('#formCliente').slideToggle();
    });
    $('#veiculo').click(function(){
      $('#formVeiculo').slideToggle();
    });
    $('#formCliente').hide();
    $('#formVeiculo').hide();
  });
</script>

<div class="container-fluid">
  <div class="row">
    <div class="col-md-4">

      <li class="btn btn-success" id="cliente">
        Cadastrar Cliente
      </li>

      <li class="btn btn-success" id="veiculo">
        Cadastrar Veiculo
      </li>

    </div>
<div class="col-md-8">
  <div class="row">
      <div class="col-md-6">
          <form action="index.php" method="post" id="formCliente">
          <p>
              <label for="">Nome</label><br>
              <input type="text" name="nome">
          </p>
          <p>
              <label for="">CNH</label><br>
              <input type="text" name="cnh">
          </p>
          <p>
              <label for="">Endereço</label><br> 
              <input type="text" name="endereco">
          </p>
          <p>
            <input type="submit" value="Cadastrar">
          </p>
          </form>
      </div>
      <div class="col-md-6">
          <form action="index.php" method="post" id="formVeiculo">
              <p>
                  <label for="">Placa</label><br>
                  <input type="text" name="placa">
              </p>
              <p>
                  <label for="">Modelo</label><br>
                  <input type="text" name="modelo">
              </p>
              <p>
                  <label for="">Cor</label><br> 
                  <input type="text" name="cor">
              </p>
              <p>
                  <label for="">Ano</label><br> 
                  <input type="text" name="ano">
              </p>
              <p>
                  <label for="">Quantidade de Passageiros</label><br> 
                  <input type="text" name="qntd_passageiro">
              </p>
              <p>
                <input type="submit" value="Cadastrar">
              </p>
          </form>
      </div>
  </div>
</div>  

`

What was modified with Francis' help.

    if($_POST)
{
    if(isset($_POST['nome']))
        CadastrarCliente($_POST['nome'],$_POST['cnh'],$_POST['endereco']);
    else if (isset($_POST['placa']))
        CadastrarVeiculo($_POST['placa'],$_POST['modelo'],$_POST['cor'],$_POST['ano'],$_POST['qntd_passageiro']);
}

I am a student of a course where I have as exercise to develop a small system of car rental where I must register data of the vehicle and customer, the functions are all right and I can already display the information on the user’s page also, I did 4 functions one to register client, for vehicle, one to display the customer information and the other for the vehicle, I also used two forms to send the same page using method post.

I’m probably missing this first php tag:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui


Complementing...

I can register client only register the vehicle together

inserir a descrição da imagem aqui

  • 1

    Puts the code in the question and not a picture pf.

  • 2

    Could you post the code? It’s hard to help with images

  • Paulo, put the code in the question that we help format.

  • posted the function code too

1 answer

1


The problem is that you are requiring variables from $_POST without first instating them.

For example:

You created your form and sent the information by the method $_POST to the page index.php, that is, you can only use these variables after the form is validated. And in your case, it’s not what you’re doing (line 7). You are asking for variables before you have created (validated the form).

Right way:

if($_POST)
{
    if(isset($_POST['id']))
        CadastrarCliente($_POST['id'], $_POST['nome'],$_POST['cnh'],$_POST['endereco']);
    else if (isset($_POST['placa']))
        CadastrarVeiculo($_POST['placa'],$_POST['modelo'],$_POST['cor'],$_POST['ano'],$_POST['qntd_passageiro']);
}
  • posted the codes now

  • I believe that now the error is not the same, since you edited the if ($_POST).

  • I modified the photo, I want when I register one not modify the other or not register the two together as is happening at the moment.

  • I recommend that you create another php, from which only runs the commands and already returns to the index.php, is easier and more practical. If you want to continue with your idea of doing everything together, I will edit my answer.

  • Okay, see if it works now.

  • I still manage to register only the second, but thanks for the help

  • good managed, thanks for the help.

  • From what you’re saying, it seems to be the case mark an answer as accepted. If you have an answer that really helped you, mark it as accepted. If you arrived at the solution yourself, post the solution as an answer. So content is more organized and easier to find in the future by other people with similar problems.

Show 3 more comments

Browser other questions tagged

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