简体   繁体   中英

Mysql query result from multiple conditions

To anyone trying to do the same:

This code respond to multiple HTML selects, and if the user press the button without filters, it displays a SELECT *.

Victor Koenders fixed the query, thank you.

As LPChip pointed out, the foreach needs two diferent variables, one that calls the function and the other that shows the table columns on a table.

The simple cuotes on the columns did not work, only when I remove them it worked, as in SELECT * FROM table WHERE variable = ´criteria´.

I marked LPChip as the answer because that damned foreach was keeping me up.

I hope this helps somebody here, this site is awesome.

public function filterFood() {

    $variable1 = $_POST['variable1'];   
    $variable2 = $_POST['variable2'];
    $variable3 = $_POST['variable3'];
    $criteria1 = $_POST['criteria1'];   
    $criteria2 = $_POST['criteria2'];
    $criteria3 = $_POST['criteria3'];

    $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    $query = "SELECT * FROM food";
    $conditions = array();

    if($criteria1 !="") {
      $conditions[] = $variable1." = '".$criteria1."'";
    }
    if($criteria2 !="") {
      $conditions[] = $variable2." = '".$criteria2."'";
    }
    if($criteria3 !="") {
      $conditions[] = $variable3." = '".$criteria3."'";
    }

    $sql = $query;
    if (count($conditions) > 0) {
      $sql .= " WHERE " . implode(' AND ', $conditions);
    }

    //$result $this->db_connection->query($sql);
    return $this->db_connection->query($sql);

    var_dump($sql);
}

And:

<?php

foreach($filter_food->filterFood() as $filtered_food) {
?>

Now I can finally go to sleep.

$result = $this->db_connection->$sql;

这是您的问题,您想做类似的事情

$result = $this->db_connection->query($sql);
foreach($filter_food->filterFood() as $filter_food)

This will never work, because you are using array $filter_food, and then you are making each result $filter_food which causes a backloop, and thus it won't work.

You could change the as $filter_food to $filtered_food or anything else to make it work.

Also, I usually write my querys like this: any column or table I use the `` quotes, and any variable I use the "..." This could solve your query property problem. Especially quoting the tables, as it might see one of the tables as a function.

Your query would become:

SELECT * FROM `food` WHERE `container_food` = "SACO" AND `animal_name_food` = "GATO"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM