How to make an empty select to pull all column results

2

I'm trying to make an empty select, which if not selected no option pulls all the results, using the AND in SELECT the form forces me to choose some option, how can I solve this? Here are the codes:

<form action="index2.php" method="post" >
<input type="hidden" name="submitted" value="true">

<label for="">Nome:
    <input type="text" name="nome" />
</label>

<label for="">Tipo:
    <select name="tipo" id="">
        <option value=""></option>
        <option value="P">Personagem</option>
        <option value="R">Reino</option>
        <option value="I">Item</option>
        <option value="A">Ação</option>
    </select>
</label>

<label for="">Vida: 
    <input type="text" name="vida">
</label>

<label for="">Força: 
    <input type="text" name="forca">
</label>

<input type="submit">

</form>

-

$nome = $_POST['nome'];
$tipo = $_POST['tipo'];
$vida = $_POST['vida'];
$forca = $_POST['forca'];
$query = "SELECT * 
FROM WoH 
WHERE NOME LIKE '%".$nome."%' 
AND 'TIPO' = '$tipo' 
AND 'VD' = '$vida'
";

Search does not work because it does not have any rows with "" value in my TYPE column. If I take the empty option, leaving the character option as default, it searches only the characters, how can I do it so that when the user wants to search the cards in ALL types, the default option brings me that result? p>     

asked by anonymous 15.05.2014 / 17:01

2 answers

2

You can do this through PHP like this:

$nome = $_POST['nome'];
$tipo = $_POST['tipo'];
$vida = $_POST['vida'];
$forca = $_POST['forca'];

$query = "SELECT * 
FROM WoH 
WHERE NOME LIKE '%".$nome."%' AND 'VD' = '$vida'";
if($tipo!="")
{
   $query .= " AND 'TIPO' = '$tipo'"; //junção sql do tipo no fim da query.
}
    
15.05.2014 / 17:12
2

Never insert POST / GET parameters directly into the SQL string. This allows SQL Injection. You can use mysql_real_escape_string to treat the string so that it stays safe and then mount the final query:

$nome = mysql_real_escape_string($_POST['nome']);
$tipo = mysql_real_escape_string($_POST['tipo']);
$vida = mysql_real_escape_string($_POST['vida']);
$forca = mysql_real_escape_string($_POST['forca']);

$query = 'SELECT * FROM WoH '.
         'WHERE NOME LIKE "%'.$nome.'%" '.
         (empty($vida)?'':'AND VD = "'.$vida.'" '.
         (empty($tipo)?'':'AND TIPO = "'.$tipo.'" ';

Warning : mysql_real_escape_string has been deprecated in PHP 5.5. The best solution is to use prepared statements.

    
16.05.2014 / 05:17