Search registered users and show same page

Asked

Viewed 158 times

-1

I have the following mistakes My head is frying too much and I can’t see the error

Notice: Undefined index: cxnome

Notice: Undefined index: search

Follows 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";
}
?>
  • 1

    I’ve tried but it’s complicated - to facilitate you could explain better how you have tried, what tried, what did not work...

  • It’s just hard to get the search to stay on the same page because as soon as the search is done it is redirected to another page

1 answer

1


Your mistake is here

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

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

A solution to this problem of yours is to put a condition of existence so that $nome receive $_POST['cxnome'] only if this is defined:

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

The same goes for $_POST['pesquisar']

  • 1

    Man I was so hot head that I end up letting simple mistakes pass and even I look several times, I don’t think the error KKKK Thank you very much!!! Thanks a lot!!

Browser other questions tagged

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