keewee279
keewee279

Reputation: 1654

PHP: How to pass multiple values to SELECT query

I am new to PHP and hope someone can help me with this.

I currently use the below lines to retrieve a value from a db and to output it as an array with the item's ID and value which works as intended.

Now I would need to do the same for multiple items so my input ($tID) would be an array containing several IDs instead of just a single ID and I would need the query to do an OR search for each of these IDs.

I was thinking of using a foreach loop for this to append " OR " to each of the IDs but am not sure if this is the right way to go - I know the below is not working, just wanted to show my thoughts here.

Can someone help me with this and tell me how to best approach this ?

My current PHP:

$content = "";
$languageFrm = $_POST["languageFrm"];
$tID = $_POST["tID"];

$stmt = $conn->prepare("SELECT tID, " . $languageFrm . " FROM TranslationsMain WHERE tID = ? ORDER BY sortOrder, " . $languageFrm);
$stmt->bind_param("s", $tID);
$stmt->execute();
$result = $stmt->get_result();
while($arr = $result->fetch_assoc()){
    $content[] = array("ID" => $arr["tID"], "translation" => $arr[$languageFrm]);
}

My thought:

foreach($tID as $ID){
    $ID . " OR ";
}

Many thanks for any help, Mike

Upvotes: 1

Views: 1300

Answers (2)

Ram Sharma
Ram Sharma

Reputation: 8819

As per above conditions you can try with implode();

implode($tID,' OR ');

You can also use IN condition instead of OR something like this.

implode($tID,' , ');

Upvotes: 0

ptkoz
ptkoz

Reputation: 2497

There are two approaches, assuming $tID is an array of IDs

Using MySQL IN() clause

This will work also when $tID is not an array, but a single scalar value.

$tID = array_map('intval', (array)$tID); // prevent SQLInjection
if(!empty($tID)) {
    $query .= ' WHERE tID IN(' . implode(',', $tId) . ')';
} else {
    $query .= ' WHERE 0 = 1';
}

Using OR clause, as you suggested

A bit more complicated scenario.

$conds = array();
foreach($tID as $ID) {
    $conds[] = 'tID = ' . intval($ID);
}

if(!empty($conds)) {
    $query .= ' WHERE (' . implode(' OR ', $conds) . ')';
} else {
    $query .= ' WHERE 0 = 1';
}

Upvotes: 2

Related Questions