P
P
Panzers2020-05-16 03:36:59
PHP
Panzers, 2020-05-16 03:36:59

Extracting data from a database with the same ID?

Hello!
There is a table that looks like this:

ID - COLOR
1A - Yellow
1B - Black
1C - Red
1D - Brown


And there is this PHP code:
$pin1 = '1A';
$pin2 = '1B';
$pin3 = '1C';
$pin4 = '1D';

$sql = "SELECT `color` FROM `pin` WHERE `id` in ('$pin1', '$pin2', '$pin3', '$pin4')";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
  
    while($row = $result->fetch_assoc()) {
        print($row["color"]."");
    }
}
else {
    echo "0 results";
}


Variables $pin1, 2, 3, 4 can be both with different values, and all with the same. When ID values ​​are not repeated in variables, then all 4 colors are displayed, but if 2 out of 4 are repeated, then only one of these two is displayed.
Suppose we have all variables with one value "1A", then only one word "Yellow" is displayed on the screen.
How can I display all 4 values, even if they are the same?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AUser0, 2020-05-16
@Panzers

Do 4 different queries, MySQL will not be able to optimize them by reducing duplicates.
It could be something like this:

SELECT (SELECT color FROM  pin WHERE id='$pin1') AS pin1, (SELECT color FROM  pin WHERE id='$pin2') AS pin2, (SELECT color FROM  pin WHERE id='$pin3') AS pin3, (SELECT color FROM  pin WHERE id='$pin4') AS pin4

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question