Indefinite Index - PHP

Asked

Viewed 980 times

-3

In my PHP code, even with Mysql and Apache linked, error appears

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

Notice: Undefined index: preco in C: xampp htdocs loja adiciona-produto.php on line 5

I believe the message is talking about the GET type request, I took 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"); ?>
  • You know what the $_GET["nome"] makes? Could explain me with your words in a succinct way?

  • I believe it serves to store the "user" data typed by the user, in case the name of the product described by him.

  • 2

    And where is this data? Where does PHP pull the values of this variable?

2 answers

1


Notice: Undefined index: name in C: xampp htdocs store add-product.php on line 4 Notice: Undefined index: preco in C: xampp htdocs loja adiciona-produto.php on line 5

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

When you spin that script, must 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?

Checking out if the values have been 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 coalescence operator (??) was launched in the PHP 7 and it would be the same as isset($_GET["nome"]) ? $_GET["nome"] : 'vazio';

Source: PHP - New features

-1

So the code of the friend really right, but it presents a flaw for those who do not want to pass anything in the variable, because you want to use on the page itself as for example a pagination code where you create a variable but at the beginning you do not pass any value in the URL ah unless you click the button, it seems that it is nothing but if you do not pay attention to the headache then will the tip.

<?php $nome = $_GET["nome"] ?? ''; // em vez de deixar a palavra 'vazio', não deixe nada $preco = $_GET["preco"] ?? ''; // em vez de deixar a palavra 'vazio', não deixe nada ?>

Even in Programming a blank space is still something is a value, and in the case it is a value that has no error.

Browser other questions tagged

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