Search system error with php

0

I'm creating a search system for users on my site. However I am facing the following error:

ThisisthecodeI'musing:

<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 this case, in the above code snippet would be line 4 . How can I resolve this error and display the search result correctly?

    
asked by anonymous 20.07.2016 / 17:51

2 answers

1

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

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

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

Another way would be to use filter_input .

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

if ($query !== false) {

    // minha lógica para consulta         

}
    
20.07.2016 / 17:53
0

You can use isset .

In this way 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 "whether it exists," or "if set," rather.

In this case it checks to see if $_GET['query'][2] exists, ie if the third character in $_GET['query'] .

This is LIGHTER faster than strlen , because it only checks for the third character, not counting the entire string, and then comparing. The difference is VERY SMALL and IMPERCEPABLE, but it does exist.

You can create this:

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

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

This is exactly the same function. ;)

    
20.07.2016 / 18:09