How do I filter my data?

Asked

Viewed 55 times

0

Good. I have a BD called vehicles, and I’m using PHP + Json for the listing. But now I need to filter them and I don’t know how to do it. I was thinking of using 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;
            }
    }
?> 
  • 1

    What do you want to do specifically? If you just filter the results according to some criteria, you don’t just use one WHERE in query?

  • wanted for example: write a tag and the tag appears

  • exactly paul

1 answer

0

I’m reusing your code ok.

<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;
}
?> 

Browser other questions tagged

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