How to check for value in an array in PHP?

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>
";

}

How to check for value in an array in PHP?

    
asked by anonymous 10.05.2014 / 17:38

4 answers

9

You can use isset to check if the variable has been defined. This way, you will only show information that nome is 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>";
   }
}
    
10.05.2014 / 17:48
5

The isset has a problem, it only reports 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 verifies if the variable is not empty.

if( !empty($_POST["nome"]) )
{
    // código
}
    
10.05.2014 / 22:26
2

On the line where it is:

$nome = $_POST["nome"];

You can change to:

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

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

    
10.05.2014 / 18:04
2

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

This is because isset() with arrays besides checking if index determines exists will also check its contents. This is where the danger lives because, in certain circumstances, such as validation algorithms, it may be interesting to have present but empty indexes.

And a check with isset() might end up harming logic and even making debugging difficult.

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

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

    
12.05.2014 / 18:40