How to check for value in a PHP array?

Asked

Viewed 917 times

4

When I enter the page PHP already has an error:

Notice: Undefined index: name in C: wamp www index.php on line 41

Here is the code:

include ("conexao.php");

$nome = $_POST["nome"];

$resul = mysql_query("SELECT * FROM funcionarios WHERE nome = '$nome'");

while($row = mysql_fetch_array($resul))
{
print "
<tr align='center'>
<td> $row[id_funcionario] </td>
<td> $row[nome] </td>
<td> $row[idade] </td>
<td> $row[sobrenome] </td>
<td> $row[senha] </td>
</tr>
";

}

Checking for value in a PHP array?

  • Execute the following code in this file: var_dump($_POST) and show us the result through the comments.

  • 2

    Unrelated to the question, but your code has a very high risk of suffering an attack called SQL Injection. I suggest reading this question after solving the problem of the variable: http://answall.com/questions/3864/

  • The question title is misplaced. The problem is an undefined array index. To avoid this error, just follow the tips posted about using isset()

4 answers

9

You can use the isset to check if the variable has been set. Thus, you will only show the information that the nome be informed:

include ("conexao.php");

if(isset($_POST["nome"]))
{
   $nome = $_POST["nome"];

   // NÃO USE mysql_query! 
   // Risco de SQL Injection.
   // Pesquise por mysqli e\ou PDO.
   $resul = mysql_query("SELECT * FROM funcionarios WHERE nome = '$nome'");

   while($row = mysql_fetch_array($resul))
   {
      print "
      <tr align='center'>
      <td> $row[id_funcionario] </td>
      <td> $row[nome] </td>
      <td> $row[idade] </td>
      <td> $row[sobrenome] </td>
      <td> $row[senha] </td>
      </tr>";
   }
}

5

The isset has a problem, it informs only if the variable was started, in your case if the variable is set to empty '' the code will be executed. I recommend using !empty, which in turn checks whether the variable is not empty.

if( !empty($_POST["nome"]) )
{
    // código
}
  • True. The ideal would be to ensure that the user enters a name other than empty before trying to list employees.

  • That, it would be even better to validate the data: check the type of content coming from the form, check the minimum and/or maximum number of characters allowed and etc.

2

On the line where:

$nome = $_POST["nome"];

You can modify to:

$nome = isset($_POST["nome"]) ? $_POST["nome"] : '';

This way will avoid the code error, but with or without POST request it will perform the query in the database, if you prefer to perform query only when there is the POST request, use the @Lucasnunes example.

2

Although much has been suggested to the use of isset() I suggest you prefer array_key_exists() instead.

That’s because isset() with arrays besides checking if I determine the index exists will also check its content. And this is where the danger lies because, in certain circumstances, such as validation algorithms, it can be interesting to have indexes present but empty.

And a check with isset() can end up damaging logic and even hindering a debugging.

Notwithstanding, isset() also requires more processing than array_key_exists() precisely because two distinct tests are made distinct for the same simple purpose.

Of course, this falls into the category of micro optimizations that is not the focus here and should only be taken into account in Applications medium-large fully developed with isset().

  • Bruno, isset is a language constructor and is much more performative than array_key_exists. Where does information come from it requires more processing?

  • When I was coding, I was kind of paranoid about performance and micro-optimizations. By not working in the area I could afford to test various particularities. I always did silly tests with microtime(). Here at SOPT I met 3v4l.org and look at the tests between one and another.

  • isset(), being a language builder consumes less system resources, but consumes more memory and has a performance almost 50% worse than array_key_exists() because in addition to testing if the input exists, it takes into account its value.

  • I re-ran the tests, doing isset and array_key_exists used only for comparison and obtained the opposite result (using the same website as you): isset (http://3v4l.org/2XAqr/perf#tabs) and array_key_exists (http://3v4l.org/k6bG7/perf#tabs)

  • Well... In yours there is a logical test, an assignment and many more iterations than mine. Maybe something that only those who can read something from source PHP can confirm happens in a real case (yours) other than a simple debug (mine).

Browser other questions tagged

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