简体   繁体   中英

Create MySQL query with IDs from results

I have aa form which let's the user select what they want to display. Now the results of this looks like that: 9, 10, 11 . These are IDs from the table.

These are the IDs of the type they what to show. I have my query already, but I want to add this part at the end of my query.

So in this case:

$query = "type_ID = $result1 or type_ID = $result2 or type_ID = $result3"

if printed out with echo:

type_ID = 9 or type_ID = 10 or type_ID = 11

How can I achieve this?

I tried to loop and it,however this did not work and I am confused how to do add the MySQL code to this.

$result = $result . $_GET['type_ID'][$i]

I'm a tad unsure of what it is you are trying to achieve but from what I understand this should do it:

<?php
$tID = $_GET['type_ID'];

$query = 'SELECT * FROM table WHERE';

$i = 0;
foreach($tID AS $id){
    if($i == 0){
        $query .= ' type_ID = ' . $id;
        $i++;
    }else{
        $query .= ' OR type_ID = ' . $id;
    }
}

Although if you are only looking for the type_ID I'd still recommend using IN() like so:

<?php
$tID = $_GET['type_ID'];

$query = "SELECT * FROM table WHERE type_ID IN (" . implode(',',$tID) . ")";

In works just like OR, just instead of having to write multiple OR you can just use a single IN() :)

你试过这个吗?

$sql = "SELECT * FROM table WHERE ".$query;

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