Indefinite Index - PHP

-3

In my PHP code, even with MySQL and Apache connected, the error appears

  

Notice: Undefined index: name in C: \ xampp \ htdocs \ store \ add-product.php on line 4

     

Notice: Undefined index: price in C: \ xampp \ htdocs \ shop \ add-product.php on line 5

I think the message is talking about the GET request, I got my code and from what I saw it has no error. How could I fix the code?

Code:

<?php include("cabecalho.php"); ?>
        <?php
        $nome = $_GET["nome"];
        $preco = $_GET["preco"];
        ?>
           <p class="alert-sucess">
            Produto <?= $nome; ?>, <?= $preco; ?> adicionado com sucesso!
           </p>
<?php include("rodape.php"); ?>
    
asked by anonymous 11.12.2018 / 17:43

1 answer

1
  

Notice: Undefined index: name in C: \ xampp \ htdocs \ store \ add-product.php on line 4   Notice: Undefined index: price in C: \ xampp \ htdocs \ shop \ add-product.php on line 5

These errors are saying that the [such] "index" is not defined. Specifically, its $_GET variable does not have the name and preco key.

When you run this script , you should pass these values via URL .

Example: http://projetoromano.com.br/index.php?nome=Romano&preco=1.99

  

Source: PHP - $ _GET

Finally:

  

How could I fix the code?

Verifying if values were passed and if not, the value becomes "empty":

<?php include("cabecalho.php"); ?>
    <?php
    $nome = $_GET["nome"] ?? 'vazio';
    $preco = $_GET["preco"] ?? 'vazio';
    ?>
       <p class="alert-sucess">
        Produto <?= $nome; ?>, <?= $preco; ?> adicionado com sucesso!
       </p>
<?php include("rodape.php"); ?>

The null coalescing operator ( ?? ) was released in PHP 7 and would be the same as isset($_GET["nome"]) ? $_GET["nome"] : 'vazio';

  

Source: PHP - New Features

    
11.12.2018 / 18:00