Search for registered users and show same page [duplicate]

-1

I have the following errors My head is frying too much and I can not see the error.

Notice: Undefined index: cxname

Notice: Undefined index: search

Follow the codes

<?php
 try {
    $con = new PDO('mysql:host=localhost;dbname=XXX', 'root', 'XXX');
 } catch (PDOException  $e) {
    print $e->getMessage();
 }
?>



 <form name="form1" method="post" action="">
  <label>
  <input name="cxnome" type="text" id="cxnome" value="" size="30">
  </label>
  <label></label>

  <label>
  &nbsp;&nbsp;
  <input type="submit" name="pesquisar" value="Pesquisar">
  </label>
&nbsp;
<label>
<input type="reset" name="Submit2" value="Limpar">
</label>
</form>




<?php

$nome=$_POST['cxnome'];
$pesquisa=$_POST['pesquisar'];

if(isset($pesquisa)&&!empty($nome))
{
$stmt = $con->prepare("SELECT * FROM usuarios WHERE nome LIKE :letra");
$stmt->bindValue(':letra', '%'.$nome.'%', PDO::PARAM_STR);
$stmt->execute();
$resultados = $stmt->rowCount();

if($resultados>=1){

echo "Resultado(s) encontrado(s): ".$resultados."<br /><br />";
while($reg = $stmt->fetch(PDO::FETCH_OBJ))
{
echo $reg->nome." - ";
echo $reg->email."<br />";
}
}
else
{
echo "Não existe usuario cadastrado";
}
}
else{
echo "Preencha o campo de pesquisa";
}
?>
    
asked by anonymous 13.07.2018 / 23:36

1 answer

1

Your error is here

<?php
$nome=$_POST['cxnome'];
$pesquisa=$_POST['pesquisar'];
...
?>

When you do this, you are assigning the value of $_POST['cxnome'] to a variable, with $_POST['cxnome'] not yet defined, since the first time you enter the page you have not yet done the form.

One solution to this problem is to put a existence condition so that $nome gets $_POST['cxnome'] only if it is set:

if (isset($_POST['cxnome'])){
  $nome=$_POST['cxnome'];
  $pesquisa=$_POST['pesquisar'];
}

The same goes for $_POST['pesquisar']

    
14.07.2018 / 02:43