Error in search system with php

Asked

Viewed 74 times

0

I am creating a user search system on my website. However I am facing the following error:

inserir a descrição da imagem aqui

This is the code I’m using:

<body>
		<h2>Resultados da tua pesquisa</h2><br />
		<?php
			$query = $_GET['query'];

			$min_length = 3;

			if (strlen($query) >= $min_length) {
				$query = htmlspecialchars($query);

				$query = mysql_real_escape_string($query);

				$raw_results = mysql_query("SELECT * FROM usuario WHERE (`nome` LIKE '%".$query."%')") or die(mysql_error());

				if (mysql_num_rows($raw_results) > 0) {
					echo "<br /><br />";
					while ($results = mysql_fetch_array($raw_results)) {
						echo '<a href="perfil.php?id='.$results["id"].'" nome="p"><br /><p nome="p"><h3>'.$results["nome"].' '.$results["apelido"].'</h3></p><br /></a><br /><hr /><br />';
					}
				}else{
					echo "<br /><h3>Não foram encontrados resultados...</h3>";
				}
			}else{
				echo "<br /><h3>Tens de escrever pelo menos 3 letras...</h3>";
			}
		?>
	</body>

The error points to line 17, which in the case, in the code snippet above would be line 4. How can I resolve this error and present the search result correctly?

2 answers

1

You are trying to capture the index that does not exist. In case query in the variable $_GET.

You can make a ternary to check if the value exists:

$query = isset($_GET['query']) ? $_GET['query'] : '';

Another way would be using filter_input.

$query = filter_input(INPUT_GET, 'query');

if ($query !== false) {

    // minha lógica para consulta         

}
  • +1 It is another solution, but I have never used it. I believe that the isset () can serve better. : S

0

You can use the isset.

Thus use:

$min_length = 3;

if ( isset( $_GET['query'][ $min_length - 1 ] ) ) {

  // Seu código quando existe mais ou igual a 3 caracteres

}else{

  // Seu código quando não existe 3 caracteres    

}

The isset checks "if it exists", or "if it is set", i.e..

In that case he checks whether the $_GET['query'][2] exists, that is if the third character in the $_GET['query'].

This is SLIGHTLY faster than the strlen, because it just checks if there is a third character, not counting the whole string and then comparing. The difference is VERY SMALL and IMPERCEPTIBLE, but there is.

You can create this:

$min_length = 3;
$valido = isset( $_GET['query'][ $min_length - 1 ] );

if ( $valido ) {
//...
}else{
//...
}

That’s exactly the same function. ;)

Browser other questions tagged

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