How do I filter my data?

0

Good. I have a DB calling vehicles, and I'm using PHP + Json for listing. But now I need to filter them out and I do not know how to do it. I was thinking about using the html but I'm not getting it either.

<?php
// header('Access-Control-Allow-Origin: *'); 
// header('Access-Control-Allow-Headers: *'); 
// header('Access-Control-Allow-Methods: GET, POST, PUT');
header('Content-Type: application/json');

$servername ="localhost";
$username ="root";
$password ="";
$dbname= "aula";

//Criar conexao

$conn = new MySQLi($servername,$username,$password,$dbname);

//Ver conexao

if($conn ->connect_error){
    die("Connection failed: " . $conn->connect_error);
}

$res = mysqli_query($conn, "SELECT * FROM veiculo");

$datarequest = array();
if ((count($_REQUEST) > 0))
    $datarequest = $_REQUEST;
$q = $datarequest['q'];
unset($datarequest['q']);
unset($_REQUEST['q']);

switch($q){
    case 'carro':{
    if ($res->num_rows > 0) {
            while($row = mysqli_fetch_assoc($res))
            $test[] = $row; 
            echo json_encode($test);
         }
    break;
            }
    }
?> 
    
asked by anonymous 21.11.2016 / 16:43

1 answer

0

I'm reusing your code okay.

<input type="text" name="marca" value="">
<input type="submit">

<?php
$sql = "SELECT * FROM veiculo";
$condicoes = null;

if ($_REQUEST['marca']) {
    // alerta critico de segurança
    // aqui não estou tratando o texto da marca
    // é preciso fazer anti-injection dos valores enviados para queries

    $marca_nome = $_GET['marca'];
    $condicoes  = 'Marca LIKE %'.$marca_nome.'%'
}

if (!empty($condicoes) {
    $sql .= ' WHERE '.$condicoes;
}

$res = mysqli_query($conn, $sql);

$datarequest = array();

if ((count($_REQUEST) > 0)) {
    $datarequest = $_REQUEST;
}

// essa parte do seu código esta bem confusa

$q = $datarequest['q'];
unset($datarequest['q']);
unset($_REQUEST['q']);

// evite usar switch quando um IF resolveria.    
switch($q) {
    case 'carro':

        if ($res->num_rows > 0) {
            while($row = mysqli_fetch_assoc($res))
                $test[] = $row; 
            echo json_encode($test);
        }
    break;
}
?> 
    
22.11.2016 / 19:07